babykick babykick - 2 years ago 89
Python Question

How to get the size of a string in Python?

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 string before writing the string to the file. What function can I use to calculate the size of the string?

Answer Source

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

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

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download