Count string length in python

Get the length of a string (number of characters) in Python

In Python, you can get the length of a string str (= the number of characters) using the built-in len() function.

See the following article on how to count the number of specific characters/substrings in a string, rather than the length of the entire string.

See the following article for the usage of len() for other types, such as list .

Get the length of a string (number of characters) with len()

By passing a string to the built-in len() function, its length (the number of characters) is returned as an integer value.

Читайте также:  Накрутка зрителей ютуб python

Full-width and half-width characters

Both full-width and half-width characters are treated as one character (length: 1).

s = 'あいうえお' print(len(s)) # 5 s = 'abcdeあいうえお' print(len(s)) # 10 

Escape sequences and special characters

In Python, special characters such as TAB are represented with a backslash, like \t . The backslash itself is represented by \\ . These special characters are considered as single characters.

s = 'a\tb\\c' print(s) # a b\c print(len(s)) # 5 

In raw strings where escape sequences are not treated specially, the string is considered as-is without being interpreted as special characters. The number of characters is also counted as-is.

s = r'a\tb\\c' print(s) # a\tb\\c print(len(s)) # 7 

The Unicode escape sequence \uXXXX is also treated as a single character.

s = '\u3042\u3044\u3046' print(s) # あいう print(len(s)) # 3 

Unicode escape sequences are not treated as special characters in raw strings.

s = r'\u3042\u3044\u3046' print(s) # \u3042\u3044\u3046 print(len(s)) # 18 

Line breaks

\n (LF: Line Feed) is also considered as a single character.

s = 'a\nb' print(s) # a # b print(len(s)) # 3 

If \r\n (CR: Carriage Return + LF: Line Feed) is used, it is counted as two characters, \r and \n .

s = 'a\r\nb' print(s) # a # b print(len(s)) # 4 

If \n and \r\n are mixed, the number of characters in each newline section is different.

s = 'abc\nabcd\r\nab' print(s) # abc # abcd # ab print(len(s)) # 12 

To handle mixed \n and \r\n , or when unsure which one is used, use the splitlines() method, which returns a list split by lines.

print(s.splitlines()) # ['abc', 'abcd', 'ab'] 

The number of elements in the list returned by splitlines() corresponds to the number of lines.

You can obtain the number of characters in each line using list comprehensions.

print([len(line) for line in s.splitlines()]) # [3, 4, 2] 

To calculate the total number of characters, use sum() with a generator expression. Generator expressions are enclosed in () instead of [] , but when used within () , as in this example, () can be omitted.

print(sum(len(line) for line in s.splitlines())) # 9 

For more information about handling line breaks, see the following article.

  • Format strings and numbers with format() in Python
  • Sort a list, string, tuple in Python (sort, sorted)
  • Remove a part of a string (substring) in Python
  • Concatenate strings in Python (+ operator, join, etc.)
  • Right-justify, center, left-justify strings and numbers in Python
  • Extract and replace elements that meet the conditions of a list of strings in Python
  • Extract a substring from a string in Python (position, regex)
  • Regular expressions with the re module in Python
  • How to use f-strings in Python
  • Convert and determine uppercase and lowercase strings in Python
  • Split strings in Python (delimiter, line break, regex, etc.)
  • Raw strings in Python
  • Search for a string in Python (Check if a substring is included/Get a substring position)
  • Replace strings in Python (replace, translate, re.sub, re.subn)
  • Reverse a list, string, tuple in Python (reverse, reversed)

Источник

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.

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.

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!

Источник

Четыре способа найти длину строки в Python

В некоторых случаях при работе со строками в Python нам необходимо определить длину строки. Сделать это можно несколькими способами, а какими — мы сейчас и узнаем.

Итак, в языке программирования Python строки относят к категории неизменяемых последовательностей, что необходимо помнить при вызове методов и функций. Теперь давайте представим, что у нас есть строка, и нам требуется найти её длину:

Сделать это можно несколькими способами.

Определяем длину строки в Python: способ № 1

Начнём с общеизвестного и наиболее популярного — использования функции len() . Эта встроенная функция возвращает количество символов в исследуемой нами строке, определяя таким образом её длину. Тут всё элементарно, и вы можете проверить код ниже на любом онлайн-компиляторе:

 
# Находим длину строки в Python с помощью функции len() str = 'otus' print(len(str))

Итогом работы функции станет следующий вывод в терминал:

Ищем длину строки в «Питоне»: способ № 2

Чтобы подсчитать количество символов в строке Python, мы можем воспользоваться циклом for и счётчиком. Тут тоже всё просто, т. к. определение длины происходит путём подсчёта числа итераций.

 
# Python-код возвращает длину строки def findLen(str): counter = 0 for i in str: counter += 1 return counter str = "otus" print(findLen(str))

Соответственно, наш вывод в консоли тоже будет равен 4.

Поиск длины строки в Python: способ № 3

Теперь давайте воспользуемся циклом while. Мы «нарежем» строку, укорачивая её на каждой итерации, в результате чего получим пустую строку и остановку цикла. А подсчёт количества итераций снова позволит нам вывести в терминал искомую длину.

 
# Python-код, возвращающий длину строки def findLen(str): counter = 0 while str[counter:]: counter += 1 return counter str = "otus" print(findLen(str))

Находим длину строки в Python: способ № 4

Теперь воспользуемся строковым методом объединения. Он принимает итеративный элемент, возвращая строку, являющуюся объединением строк в итерируемом нами элементе. Разделитель между элементами — исходная строка, для которой и вызывается метод. Применение метода объединения с последующим подсчётом объединённой строки в исходной строке тоже позволит нам получить длину строки на «Питоне».

 
# Python-код, возвращающий длину строки def findLen(str): if not str: return 0 else: some_random_str = 'py' return ((some_random_str).join(str)).count(some_random_str) + 1 str = "otus" print(findLen(str))

Как и во всех примерах выше, в консоль выведется количество символов в строе ‘otus’, равное 4. Вот и всё!

Хотите знать про Python гораздо больше? Записывайтесь на наш курс для продвинутых разработчиков:

Источник

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