How to find the size of a string in Python?

–1 vote
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?
Aug 6, 2018 in Python by bug_seeker
• 15,350 points
73 views

2 answers to this question.

–1 vote
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.

Hope this would help you @bug_seeker
answered Aug 6, 2018 by Priyaj
• 56,520 points
0 votes

following way to find length of string 

x = input("Enter a string:")
counter = 0 # count the character in string 
for s in x:
      counter = counter+1
print("Length of the input string is:", counter)

output

Enter a string: rajesh
Length of the input string is:6

i want to say somethings string is very important in python so if you know more about python and string concept in python than you can join

best python training in Delhi

answered Mar 29 by rajesh
• 1,210 points
Hey @rk, consider this to be the last warning. Please Refrain from posting promotional content on the Community. It is not relevant and we'd like to keep the community clean.

Related Questions In Python

0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,340 points
71 views
0 votes
1 answer
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,572 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 173 views
+4 votes
6 answers
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8 in Python by rajesh
• 1,210 points
54 views
0 votes
2 answers

How do I connect to a MySQL Database in Python?

connect mysql database with python import MySQLdb db = ...READ MORE

answered Mar 28 in Python by rajesh
• 1,210 points
124 views