184

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
babykick
  • 1,923
  • 2
  • 12
  • 8
  • 2
    "what function can i use to calculate the size of the string"? What tutorial are you using to learn Python? Please **update** the question with some information on where and how you're learning Python. – S.Lott Feb 11 '11 at 10:58
  • 2
    i learn python by myself,now i know the len(str) can return the size of string,the size depends on the coding of the str. – babykick Feb 11 '11 at 15:03
  • What will be the size of the file after writing it? Let's assume the file was of zero sizes before writing. – Vicky Gupta Nov 02 '20 at 16:52

7 Answers7

309

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.

Frankline
  • 40,277
  • 8
  • 44
  • 75
user225312
  • 126,773
  • 69
  • 172
  • 181
  • 48
    `sys.getsizeof` returns the number of bytes the Python object occupies in memory. That isn't going to be useful for writing to a file in any circumstances. – Duncan Feb 11 '11 at 10:23
  • thanks,but sys.getsizeof(s) is just the size of the file? or the size of python object? – babykick Feb 11 '11 at 14:36
  • 10
    @cryanbhu I don't know why the OP wanted the size and that would affect the answer, but probably most useful would be `len(s.encode('utf8'))` or whatever other encoding is going to be used when writing to the file. Also, if they also want a terminating null then they'll need to add 1 for that. – Duncan Jul 31 '18 at 08:35
44

Python 3:

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

Python 2:

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Igor Bendrup
  • 2,637
  • 2
  • 16
  • 15
9
>>> s = 'abcd'
>>> len(s)
4
Michal Chruszcz
  • 2,452
  • 16
  • 20
4

You also may use str.len() to count length of element in the column

data['name of column'].str.len() 
1

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 "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape
digitalnomd
  • 1,380
  • 12
  • 21
1

Do you want to find the length of the string in the Python language? If you want to find the length of the word, you can use the len function.

string = input("Enter the string: ")

print("The string length is: ", len(string))

Output:

Enter the string: viral

The string length is: 5

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1 - why to add similar answer as the accepted one? 2 - your output is similar with your code, edit it or consider removing this redundant and incomplete answer... – Ruli Oct 15 '20 at 16:35
0

The responses provided are apt, but it is important to note that in Python, blank spaces are also considered characters.

However, if one wishes to create a function that requires counting total characters in someone’s name for instance, it may be necessary to remove blank spaces. This can easily be accomplished using the .replace() method.

For example:

name = "Steve Wozniak"
number = len(name.replace(" ", ""))
print(number)

The output here is 12 (excluding blank space) instead of 13 (including blank space).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ace Bliss
  • 11
  • 3
  • There are [2,161,081 Python questions](https://stackoverflow.com/questions/tagged/python). This sounds like an answer to a different question, like *[How can I count characters in a string without the white spaces using Python?](https://stackoverflow.com/questions/60969971/)*. – Peter Mortensen Aug 31 '23 at 14:41