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
user225312's answer is correct:
A. To count number of characters in str object, you can use len() function:
>>> print(len('please anwser my question'))
25
B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function
>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50
It gets complicated for Python 2.
A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.
Sometimes it will be equal to character count:
>>> print(len('abc'))
3
But sometimes, it won't:
>>> print(len('йцы')) # String contains Cyrillic symbols
6
That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:
>>> print(len('йцы'.decode('utf8'))) #String contains Cyrillic symbols
3
B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object
>>> print(getsizeof('йцы'))
27
>>> print(getsizeof('йцы'.decode('utf8')))
32