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?
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?
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.If you are talking about the length of the string, you can use
len()
:If you need the size of the string in bytes, you need
sys.getsizeof()
:Also, don't call your string variable
str
. It shadows the built-instr()
function.Python 3.*:
The user225312's answer is correct:
A. To count number of characters in
str
object, you can uselen()
function:B. To get memory size in bytes allocated to store
str
object, you can usesys.getsizeof()
functionPython 2.*:
It's getting complicated for Python 2.*.
A. The
len()
function in Python 2 returns count of bytes allocated to store encoded characters in astr
object.Sometimes it will be equal to character count:
But sometimes, it won't:
That's because
str
can use variable-length encoding internally. So, to count characters instr
you should know which encoding yourstr
object is using. Then you can convert it tounicode
object and get character count:B. The
sys.getsizeof()
function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string objectP.S. I've tested my code samples under Anaconda Python on 32-bit Windows
You also may use str.len() to count length of element in the column