How to get the size of a string in Python?

前端 未结 6 1727
说谎
说谎 2020-11-30 19:59

For example, I get a string:

str = \"please answer my question\"

I want to write it to a file.

But I need to know the size of the s

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 20:41

    The most Pythonic way is to use the len(). Keep in mind that the '\' character in escape sequences is not counted and can be dangerous if not used correctly.

    >>> len('foo')
    3
    >>> len('\foo')
    3
    >>> len('\xoo')
      File "", line 1
    SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape
    

提交回复
热议问题