How to get the size of a string in Python?

0 votes

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?

Jun 4, 2018 in Python by charlie_brown
• 7,720 points
90 views

1 answer to this question.

0 votes

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 str. It shadows the built-in str() function.

answered Jun 4, 2018 by ariaholic
• 7,340 points

Related Questions In Python

–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29 in Python by rajesh
• 1,210 points
83 views
0 votes
0 answers

How to get the ASCII values of a character in python?

Is there a function for this task ...READ MORE

Jul 17 in Python by Waseem
• 4,480 points
20 views
0 votes
1 answer

How to print first character of each word in upper case of a string in Python

You can use split() using space as ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
1,838 views
0 votes
1 answer

How can I get the count of a list in Python?

len() >>> mylist=[] >>> print len(mylist) 0 READ MORE

answered Dec 12, 2018 in Python by charlie_brown
• 7,720 points
69 views
0 votes
1 answer
0 votes
1 answer

How to get permutations of list or a set in Python?

Permutation is an arrangement of objects in ...READ MORE

answered Jul 11 in Python by Neel
• 3,010 points
40 views
0 votes
1 answer

How to get a list of built in modules in Python?

simply open the python shell and type ...READ MORE

answered Aug 1 in Python by Arvind
• 2,960 points
51 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by ariaholic
• 7,340 points
2,448 views
0 votes
1 answer

How does Python know whether a variable in the class is a method or a variable?

In python objects/variables are wrapped into methods ...READ MORE

answered Sep 18, 2018 in Python by ariaholic
• 7,340 points
46 views