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
• 14,980 points
50 views

2 answers to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
–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,140 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,320 points
49 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,172 views
0 votes
1 answer
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
54 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
38 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
75 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.