How to get the size of a string in Python?

前端 未结 6 1729
说谎
说谎 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:53

    If you are talking about the length of the string, you can use len():

    >>> s = 'please answer my question'
    >>> len(s)  # number of characters in s
    25
    

    If you need the size of the string in bytes, you need sys.getsizeof():

    >>> import sys
    >>> sys.getsizeof(s)
    58
    

    Also, don't call your string variable str. It shadows the built-in str() function.

提交回复
热议问题