Python length of word

Use this:

s = "python is pretty fun to use"
[len(x) for x in s.split()]

example output:

>>> [len(x) for x in s.split()]
[6, 2, 6, 3, 2, 3]

What’s going on in the background?

s.split() breaks on the white space in the string and returns each word in the sentence in a list:

>>> s.split()
['python', 'is', 'pretty', 'fun', 'to', 'use']

Then we take the len() of each of those words to get the word’s length. After that, we take each length and append it to a list so that it can be conveniently returned as the result.

That all happens in this list comprehension:

[len(x) for x in s.split()]

Still a little confused? This is conceptually the same thing just broken down more explicitly:

results = []
for x in s.split():
    word_length = len(x)
    results.append(word_length)
print results 

If you’d like them printed out separately, like in your question, use:

for x in [len(x) for x in s.split()]: 
    print x

What is 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
  2. Empty
  3. Collection
  4. Type Error
  5. Dictionary

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

1. Using the built-in function len()

# Python code to demonstrate string length  
# using len 

str = 'Latracal'
print(len(str))

output:

8

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))

output:

8

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)) 

output:

17

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))

output:

17

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(""))

Output:

10

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))

Output:

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!

We sometimes come through the situations where we require to get all the words lengths present in the string, this can be a tedious task done using naive method. Hence having shorthands to perform this task is always useful. Let’s discuss certain ways to achieve this. 

Method #1 : Using split() + len() Using split function, we can split the string into a list of words and is most generic and recommended method if one wished to accomplish this particular task. But drawback is that it fails in the cases in string contains punctuation marks. The len() is used to compute string length. 

Python3

test_string = "Geeksforgeeks is best Computer Science Portal"

print ("The original string is : " + test_string)

res = list(map(len, test_string.split()))

print ("The list of words lengths is : " + str(res))

Output : 

The original string is : Geeksforgeeks is best Computer Science Portal
The list of words lengths is : [13, 2, 4, 8, 7, 6]

Time complexity: O(n)

Space complexity: O(n), where n is length of string.

  Method #2 : Using regex( findall() ) + len() In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in string using split can fail and hence requires regular expressions to perform this task. findall function returns the list after filtering the string and extracting words ignoring punctuation marks. The len() is used to compute string length. 

Python3

import re

test_string = "Geeksforgeeks, is best @

print ("The original string is : " + test_string)

res = list(map(len, re.findall(r'w+', test_string)))

print ("The list of words lengths is : " + str(res))

Output : 

The original string is : Geeksforgeeks is best Computer Science Portal
The list of words lengths is : [13, 2, 4, 8, 7, 6]

Time complexity: O(n), where n is the length of the test_list. The regex( findall() ) + len() takes O(n) time
Auxiliary Space: O(n), extra space of size n is required

Method #3 : Using numpy

Note: Install numpy module using command “pip install numpy”

Python3

import numpy as np

test_string = "Geeksforgeeks is best Computer Science Portal"

print ("The original string is : " + test_string)

res = np.char.str_len(test_string.split())

print ("The list of words lengths is : " + str(res.tolist()))

Output:

The original string is : Geeksforgeeks is best Computer Science Portal
The list of words lengths is : [13, 2, 4, 8, 7, 6]
 

Another way to find the word length in a string is to use numpy. The numpy library has a function numpy.char.str_len() which can be used to find the length of each word in the string.

Time complexity: O(n)

Space complexity: O(n)

Method #4 : Using map()

In this approach, we first split the string into individual words using the split() method, which returns a list of words. We then use a generator expression to iterate over the words in the list, and get their lengths using the len() function. The resulting generator object is passed as the second argument to the map() function, which applies the len() function to each element of the generator and returns an iterator of the resulting lengths.

Finally, we convert the iterator to a list using the list() function, and return the resulting list of lengths.

In the example usage, we call the function with a sample string s. The output will be a list of integers representing the lengths of all the words in the string. In this case, the output will be [4, 2, 1, 6, 6], which corresponds to the lengths of the words “This”, “is”, “a”, “sample”, and “string”, respectively.

This approach using a generator expression and the map() function may be more memory-efficient than the previous approaches using list comprehensions, as it avoids creating a new list to store the lengths of the words. Instead, it produces the lengths as an iterator, which can be converted to a list if needed.

Python3

def word_lengths(s):

    lengths = map(len, (word for word in s.split())) 

    return list(lengths)

s = "This is a sample string"

result = word_lengths(s)

print(result) 

Time complexity: O(n)

Space complexity: O(n)

Теги: 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. Вот и всё!

Материал написан на основе статьи — «Find length of a string in python (4 ways)».

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

Python_970x90-20219-8b1a8e.png

What is len() in Python? How to Use the len() Function to Find the Length of a String

In programming languages, getting the length of a particular data type is a common practice.

Python is no different because you can use the built-in len() function to get the length of a string, tuple, list, dictionary, or any other data type.

In this article, I’m going to show you how to get the length of a string with the len() function.

Basic Syntax for len() in Python

To use the len() function to get the length of a data type, assign the data type to a variable, then pass the variable name to the len() function.

Like this:

len(variableName)

When you use the len() function to get the length of a string, it returns the number of characters in the string – including the spaces.

Here are 3 examples to show you how it works:

name = "freeCodeCamp"
print(len(name))

# Output: 12

This means there are 12 characters in the string.

founder = "Quincy Larson"
print(len(founder))

# Output: 13

This means there are 13 characters in the string.

description = "freeCodeCamp is a platform for learning how to code for free"
print(len(description))

# Output: 60

This means there are 60 characters in the string.

How len() Works with Other Data Types in Python

You might be wondering how the len() function works on other data types such as lists and tuples.

When you use the len() function on a data type like tuple or list, it returns the number of items in the tuple or list, not the number of characters.

For example, 3 gets returned for the length of the tuple below, not the number of characters of the words in it.

langs = ("Python", "JavaScript", "Golang")
print(len(langs))

# Output: 3

So it just depends on the data type you’re working with.

Conclusion

In this article, you learned how to get the length of a string – the number of characters.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Python last word in line
  • Python and excel windows
  • Python if word not in list
  • Python and excel programming
  • Python if word in array