String length function in python

How to get the size (length) of a string in Python?

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?

«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.

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.

What will be the size of the file after writing it? Let’s assume the file was of zero sizes before writing.

7 Answers 7

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.

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.

@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.

Python 3:

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('йцы')) # 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 

Источник

Читайте также:  Python цикл while loop

5 Best Ways to Find Python String Length

Python String Length

Python string length is the function through which we find the length of the string. There is an inbuilt function called len() in python, so this len() function finds the length of the given string, array, list, tuple, dictionary, etc.

Through the len() function, we can optimize the performance of the program. The number of elements stored in the object is never calculated, so len() helps provide the number of elements.

Syntax

Parameters

String : This will calculate the length of the value passed in the string variable.

Return Value

It will return an interger value i.e. the length of the given string.

Various Type Of Return Value

1. String:

It is used to return the number of characters present in the string, including punctuation, space, and all types of special characters. However, it would help if you were careful while using the len of a Null variable.

2. Empty:

In this the return call has the zero characters, but it is always None.

3. Collections:

The len() built in function return the number of elements in the collection.

4. Type Error:

Len function always depends on the type of the variable passed to it. A Non-Type len() does not have any built-in support.

5. Dictionary:

In this, each pair is counted as one unit. However, Keys and values are not independent in the dictionary.

Ways to find the length of string in Python

Ways to find the length of string

1. Using the built-in function len()

# Python code to demonstrate string length # using len str = 'Latracal' print(len(str))

Explanation:

In this code, we have taken str as the variable in which we have stored the string named ‘Latracal’ and then applied the len() in which we have put str in between. so the output came is 8 as the word ‘Latracal‘ contains 8 characters.

2. Using for loop to Find the length of the string in python

A string can be iterated over easily and directly in for loop. By maintaining a count of the number of iterations will result in the length of the string.

# Python code to demonstrate string length # using for loop # Returns length of string def findLength(str): counter = 0 for i in str: counter += 1 return counter str = "Latracal" print(findLength(str))

Explanation:

In this code, we have used for loop to find the length of the string. Firstly, we have taken an str variable that we have given ‘Latracal’ as the string. Secondly, we have called the findLength function in which we have counter equals 0, After that, for loop was written from 0 to string, and the counter value gets increased by 1 at a time. At last, we have printed the counter value.

Читайте также:  Javascript object with key and value

3. Using while loop and Slicing

We slice a string making it shorter by 1 at regular intervals to time with each iteration till the string is the empty string. This is when the while loop stops. By maintaining a count of the number of iterations will result in the length of the string.

# Python code to demonstrate string length # using while loop. # Returns length of string def findLength(str): count = 0 while str[count:]: count = count + 1 return count str = "LatracalSolutions" print(findLength(str))

Explanation:

In this code, we have used for loop to find the length of the string. Firstly, we have taken an str variable in which we have given ‘LatracalSolutions’ as the string. Secondly, we have called the findLength function in which we have set the value of count equals 0. Thirdly, then applied the while loop in which we are slicing the value of str by one at each iteration till the string becomes empty. And at last, returned the count value.

4. Using string methods join and count

The join method of strings takes in an iteration and returns a string which is the concatenation of the iteration strings. The separator present in the between of elements is the original string on which the method is called. Using the join and count method, the joined string in the original string will also result in the string’s length.

# Python code to demonstrate string length # using join and count # Returns length of string def findLength(str): if not str: return 0 else: some_random_str = 'py' return ((some_random_str).join(str)).count(some_random_str) + 1 str = "LatracalSolutions" print(findLength(str))

Explanation:

In this code, we have used for loop to find the length of the string. Firstly, we have taken an str variable in which we have given ‘LatracalSolutions’ as the string. Secondly, then we have called the findLength function in which we have applied if and else function in which if contains the conditions that if the string is empty, it should return 0; otherwise, the else part will work. We have taken some random string ‘py’ in which the main string will get join by the iteration, and the count value will increase till the string becomes empty. After that, the output gets printed.

5. Using getsizeof() method to Find Length Of String In Python

This method is used to find the object’s storage size that occupies some space in the memory.

Note: This method is only applicable for normal ascii letters. If you have a special character it’ll not work, as it uses the size of the string in bytes. So be careful while using it!

import sys s = "pythonpool" print(sys.getsizeof(s) - sys.getsizeof(""))

Explanation:

Here, we have used the sys module which is inbuilt in python. then we have to take a string s and using the sys module with the getsizeof() method printed the length of the string.

Читайте также:  Php utf8 mysql select

Example to Find Length of String in Python

# Python code to demonstrate string length # testing len() str1 = "Welcome to Latracal Solutions Python Tutorials" print("The length of the string is :", len(str1))
The length of the string is : 46

Must Read

Summary: Python String Length

We’ve seen all 5 different ways of finding the string length, but in conclusion, only one of them is practical. In-built len() keyword is the best way to find the length of the string in any type of format.

  • Python len() is a built-in function. You can use the len() to find the length of the given string, array, list, tuple, dictionary, etc.
  • String: This will calculate the length of the value passed in the string variable.
  • Return value: It will return an integer value i.e. the length of the given string.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Источник

How to calculate the length of the string in python

Hello i am a student and i have a few error with my code can anyone help me. The question is to enter enter a list of words and integer number and return the words if the length of the words is more than the integer. This is my answer.

def filter_long_words(string): string = raw_input("Enter a words : ") n = raw_input("Enter an integer : ") count = 0 for letter in string: count = count + 1 print "The total string are : ", count return count filter_long_words(string) if count > n: print string 

While reading integer, cast the return of raw_input . To get the length of the string use len() , and compare with the integer using ==

5 Answers 5

U can get the length of any string with len()

In your question you stated that the instruction was to:

return the words if the length of the words is more than the integer.

The below code will do that:

my_str = raw_input("Enter a word: ") n = raw_input("Enter an integer: ") def filter_long_words(my_str, n): if len(my_str) > int(n): return my_str # assigns the results of my_string to some_word some_word = filter_long_words(my_str, n) print some_word 

In response to your question in the comments:

def filter_long_words(): my_str = raw_input("Enter a word: ") n = raw_input("Enter an integer: ") if len(my_str) > int(n): return my_str # assigns the results of my_string to some_word some_word = filter_long_words() print some_word 

One last example. Lets say you are entering several words as one big string.

We can use .split() to get each word and test it separately.

# simulates raw input of 4 words being typed in at once. list_of_words_as_a_string = "One Two Three Four" n = raw_input("Enter an integer: ") def filter_long_words(word, n): if len(word) > int(n): print word return word # this is only useful if you are doing something with the returned word. for word in list_of_words_as_a_string.split(): filter_long_words(word, n) 

Results when using 3 as the integer:

Enter an integer: 3 Three Four 

Источник

Оцените статью