Длина строки python как найти

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Strings in Python are immutable sequences of Unicode code points. Given a string, we need to find its length. Examples:

    Input : 'abc'
    Output : 3
    
    Input : 'hello world !'
    Output : 13
    
    Input : ' h e l   l  o '
    Output :14

    Methods#1:

    • Using the built-in function len. The built-in function len returns the number of items in a container. 

    Python3

    str = "geeks"

    print(len(str))

    Method#2:

    • Using for loop and in operator. A string can be iterated over, directly in a for loop. Maintaining a count of the number of iterations will result in the length of the string. 

    Python3

    def findLen(str):

        counter = 0   

        for i in str:

            counter += 1

        return counter

    str = "geeks"

    print(findLen(str))

    Method#3:

    • Using while loop and Slicing. We slice a string making it shorter by 1 at each iteration will eventually result in an empty string. This is when while loop stops. Maintaining a count of the number of iterations will result in the length of the string. 

    Python3

    def findLen(str):

        counter = 0

        while str[counter:]:

            counter += 1

        return counter

    str = "geeks"

    print(findLen(str))

    Method#4:

    • Using string methods join and count. The join method of strings takes in an iterable and returns a string which is the concatenation of the strings in the iterable. The separator between the elements is the original string on which the method is called. Using join and counting the joined string in the original string will also result in the length of the string. 

    Python3

    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 = "geeks"

    print(findLen(str))

    Method:5:

    • Using reduce method. Reduce method is used to iterate over the string and return a result of collection element provided to the reduce function. We will iterate over the string character by character and count 1 to result each time. 

    Python3

    import functools

    def findLen(string):

        return functools.reduce(lambda x,y: x+1, string, 0)

    string = 'geeks'

    print(findLen(string))

    Output:

    5

    Method:6:

    • Using sum() and list comprehension function. We use list comprehension for iterating over the string and sum function to sum total characters in string 

    Python3

    def findLen(string):

        return sum( 1 for i in string);

    string = 'geeks'

    print(findLen(string))

    Output:

    5

    Method 7: Using enumerate function

    Python3

    string = "gee@1ks"

    s = 0

    for i, a in enumerate(string):

        s += 1

    print(s)

    Last Updated :
    20 Dec, 2022

    Like Article

    Save Article

    Теги: python, питон, поиск, строка, пайтон, длина

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

    Python_Pro_970x90-20219-1c8674.png

    Итак, в языке программирования 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_Pro_970x550-20219-0846c7.png

    Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python’s len() Function

    In many situations, you’ll need to find the number of items stored in a data structure. Python’s built-in function len() is the tool that will help you with this task.

    There are some cases in which the use of len() is straightforward. However, there are other times when you’ll need to understand how this function works in more detail and how to apply it to different data types.

    In this tutorial, you’ll learn how to:

    • Find the length of built-in data types using len()
    • Use len() with third-party data types
    • Provide support for len() with user-defined classes

    By the end of this article, you’ll know when to use the len() Python function and how to use it effectively. You’ll know which built-in data types are valid arguments for len() and which ones you can’t use. You’ll also understand how to use len() with third-party types, such as ndarray in NumPy and DataFrame in pandas, and with your own classes.

    Getting Started With Python’s len()

    The function len() is one of Python’s built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types. However, not all data types are valid arguments for len().

    You can start by looking at the help for this function:

    >>>

    >>> help(len)
    Help on built-in function len in module builtins:
    len(obj, /)
        Return the number of items in a container.
    

    The function takes an object as an argument and returns the length of that object. The documentation for len() goes a bit further:

    Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). (Source)

    When you use built-in data types and many third-party types with len(), the function doesn’t need to iterate through the data structure. The length of a container object is stored as an attribute of the object. The value of this attribute is modified each time items are added to or removed from the data structure, and len() returns the value of the length attribute. This ensures that len() works efficiently.

    In the following sections, you’ll learn about how to use len() with sequences and collections. You’ll also learn about some data types that you cannot use as arguments for the len() Python function.

    Using len() With Built-in Sequences

    A sequence is a container with ordered items. Lists, tuples, and strings are three of the basic built-in sequences in Python. You can find the length of a sequence by calling len():

    >>>

    >>> greeting = "Good Day!"
    >>> len(greeting)
    9
    
    >>> office_days = ["Tuesday", "Thursday", "Friday"]
    >>> len(office_days)
    3
    
    >>> london_coordinates = (51.50722, -0.1275)
    >>> len(london_coordinates)
    2
    

    When finding the length of the string greeting, the list office_days, and the tuple london_coordinates, you use len() in the same manner. All three data types are valid arguments for len().

    The function len() always returns an integer as it’s counting the number of items in the object that you pass to it. The function returns 0 if the argument is an empty sequence:

    >>>

    >>> len("")
    0
    >>> len([])
    0
    >>> len(())
    0
    

    In the examples above, you find the length of an empty string, an empty list, and an empty tuple. The function returns 0 in each case.

    A range object is also a sequence that you can create using range(). A range object doesn’t store all the values but generates them when they’re needed. However, you can still find the length of a range object using len():

    >>>

    >>> len(range(1, 20, 2))
    10
    

    This range of numbers includes the integers from 1 to 19 with increments of 2. The length of a range object can be determined from the start, stop, and step values.

    In this section, you’ve used the len() Python function with strings, lists, tuples, and range objects. However, you can also use the function with any other built-in sequence.

    Using len() With Built-in Collections

    At some point, you may need to find the number of unique items in a list or another sequence. You can use sets and len() to achieve this:

    >>>

    >>> import random
    
    >>> numbers = [random.randint(1, 20) for _ in range(20)]
    
    >>> numbers
    [3, 8, 19, 1, 17, 14, 6, 19, 14, 7, 6, 1, 17, 10, 8, 14, 17, 10, 2, 5]
    
    >>> unique_numbers = set(numbers)
    {1, 2, 3, 5, 6, 7, 8, 10, 14, 17, 19}
    
    >>> len(unique_numbers)
    11
    

    You generate the list numbers using a list comprehension, and it contains twenty random numbers ranging between 1 and 20. The output will be different each time the code runs since you’re generating random numbers. In this particular run, there are eleven unique numbers in the list of twenty randomly generated numbers.

    Another built-in data type that you’ll use often is the dictionary. In a dictionary, each item consists of a key-value pair. When you use a dictionary as an argument for len(), the function returns the number of items in the dictionary:

    >>>

    >>> len({"James": 10, "Mary": 12, "Robert": 11})
    3
    
    >>> len({})
    0
    

    The output from the first example shows that there are three key-value pairs in this dictionary. As was the case with sequences, len() will return 0 when the argument is either an empty dictionary or an empty set. This leads to empty dictionaries and empty sets being falsy.

    Exploring len() With Other Built-in Data Types

    You can’t use all built-in data types as arguments for len(). For data types that don’t store more than one item within them, the concept of length isn’t relevant. This is the case with numbers and Boolean types:

    >>>

    >>> len(5)
    Traceback (most recent call last):
        ...
    TypeError: object of type 'int' has no len()
    
    >>> len(5.5)
    Traceback (most recent call last):
         ...
    TypeError: object of type 'float' has no len()
    
    >>> len(True)
    Traceback (most recent call last):
         ...
    TypeError: object of type 'bool' has no len()
    
    >>> len(5 + 2j)
    Traceback (most recent call last):
         ...
    TypeError: object of type 'complex' has no len()
    

    The integer, float, Boolean, and complex types are examples of built-in data types that you can’t use with len(). The function raises a TypeError when the argument is an object of a data type that doesn’t have a length.

    You can also explore whether it’s possible to use iterators and generators as arguments for len():

    >>>

    >>> import random
    
    >>> numbers = [random.randint(1, 20) for _ in range(20)]
    >>> len(numbers)
    20
    
    >>> numbers_iterator = iter(numbers)
    >>> len(numbers_iterator)
    Traceback (most recent call last):
         ...
    TypeError: object of type 'list_iterator' has no len()
    
    >>> numbers_generator = (random.randint(1, 20) for _ in range(20))
    >>> len(numbers_generator)
    Traceback (most recent call last):
         ...
    TypeError: object of type 'generator' has no len()
    

    You’ve already seen that a list has a length, meaning you can use it as an argument in len(). You create an iterator from the list using the built-in function iter(). In an iterator, each item is fetched whenever it’s required, such as when the function next() is used or in a loop. However, you can’t use an iterator in len().

    You get a TypeError when you try to use an iterator as an argument for len(). As the iterator fetches each item as and when it’s needed, the only way to measure its length is to exhaust the iterator. An iterator can also be infinite, such as the iterator returned by itertools.cycle(), and therefore its length can’t be defined.

    You can’t use generators with len() for the same reason. The length of these objects can’t be measured without using them up.

    Exploring len() Further With Some Examples

    In this section, you’ll learn about some common use cases for len(). These examples will help you understand better when to use this function and how to use it effectively. In some of the examples, you’ll also see cases where len() is a possible solution but there may be more Pythonic ways of achieving the same output.

    Verifying the Length of a User Input

    A common use case of len() is to verify the length of a sequence input by a user:

    # username.py
    
    username = input("Choose a username: [4-10 characters] ")
    
    if 4 <= len(username) <= 10:
        print(f"Thank you. The username {username} is valid")
    else:
        print("The username must be between 4 and 10 characters long")
    

    In this example, you use an if statement to check if the integer returned by len() is greater than or equal to 4 and less than or equal to 10. You can run this script and you’ll get an output similar to the one below:

    $ python username.py
    Choose a username: [4-10 characters] stephen_g
    Thank you. The username stephen_g is valid
    

    The username is nine characters long in this case, so the condition in the if statement evaluates to True. You can run the script again and input an invalid username:

    $ python username.py
    Choose a username: [4-10 characters] sg
    The username must be between 4 and 10 characters long
    

    In this case, len(username) returns 2, and the condition in the if statement evaluates to False.

    Ending a Loop Based on the Length of an Object

    You’ll use len() if you need to check when the length of a mutable sequence, such as a list, reaches a specific number. In the following example, you ask the user to enter three username options, which you store in a list:

    # username.py
    
    usernames = []
    
    print("Enter three options for your username")
    
    while len(usernames) < 3:
        username = input("Choose a username: [4-10 characters] ")
        if 4 <= len(username) <= 10:
            print(f"Thank you. The username {username} is valid")
            usernames.append(username)
        else:
            print("The username must be between 4 and 10 characters long")
    
    print(usernames)
    

    You’re now using the result from len() in the while statement. If the user enters an invalid username, you don’t keep the input. When the user enters a valid string, you append it to the list usernames. The loop repeats until there are three items in the list.

    You could even use len() to check when a sequence is empty:

    >>>

    >>> colors = ["red", "green", "blue", "yellow", "pink"]
    
    >>> while len(colors) > 0:
    ...     print(f"The next color is {colors.pop(0)}")
    ...
    The next color is red
    The next color is green
    The next color is blue
    The next color is yellow
    The next color is pink
    

    You use the list method .pop() to remove the first item from the list in each iteration until the list is empty. If you’re using this method on large lists, you should remove items from the end of the list as this is more efficient. You can also use the deque data type from the collections built-in module, which allows you to pop from the left efficiently.

    There’s a more Pythonic way of achieving the same output by using the truthiness of sequences:

    >>>

    >>> colors = ["red", "green", "blue", "yellow", "pink"]
    
    >>> while colors:
    ...    print(f"The next color is {colors.pop(0)}")
    ...
    The next color is red
    The next color is green
    The next color is blue
    The next color is yellow
    The next color is pink
    

    An empty list is falsy. This means that the while statement interprets an empty list as False. A non-empty list is truthy, and the while statement treats it as True. The value returned by len() determines the truthiness of a sequence. A sequence is truthy when len() returns any non-zero integer and falsy when len() returns 0.

    Finding the Index of the Last Item of a Sequence

    Imagine you want to generate a sequence of random numbers in the range 1 to 10 and you’d like to keep adding numbers to the sequence until the sum of all the numbers exceeds 21. The following code creates an empty list and uses a while loop to populate the list:

    >>>

    >>> import random
    
    >>> numbers = []
    >>> while sum(numbers) <= 21:
    ...    numbers.append(random.randint(1, 10))
    
    >>> numbers
    [3, 10, 4, 7]
    
    >>> numbers[len(numbers) - 1]
    7
    
    >>> numbers[-1]  # A more Pythonic way to retrieve the last item
    7
    
    >>> numbers.pop(len(numbers) - 1)  # You can use numbers.pop(-1)
    7
    
    >>> numbers
    [3, 10, 4]
    

    You append random numbers to the list until the sum exceeds 21. The output you’ll get will vary as you’re generating random numbers. To display the last number in the list, you use len(numbers) and subtract 1 from it since the first index of the list is 0. Indexing in Python allows you to use the index -1 to obtain the last item in a list. Therefore, although you can use len() in this case, you don’t need to.

    You want to remove the last number in the list so that the sum of all numbers in the list doesn’t exceed 21. You use len() again to work out the index of the last item in the list, which you use as an argument for the list method .pop(). Even in this instance, you could use -1 as an argument for .pop() to remove the last item from the list and return it.

    Splitting a List Into Two Halves

    If you need to split a sequence into two halves, you’ll need to use the index that represents the midpoint of the sequence. You can use len() to find this value. In the following example, you’ll create a list of random numbers and then split it into two smaller lists:

    >>>

    >>> import random
    
    >>> numbers = [random.randint(1, 10) for _ in range(10)]
    >>> numbers
    [9, 1, 1, 2, 8, 10, 8, 6, 8, 5]
    
    >>> first_half = numbers[: len(numbers) // 2]
    >>> second_half = numbers[len(numbers) // 2 :]
    
    >>> first_half
    [9, 1, 1, 2, 8]
    >>> second_half
    [10, 8, 6, 8, 5]
    

    In the assignment statement where you define first_half, you use the slice that represents the items from the beginning of numbers up to the midpoint. You can work out what the slice represents by breaking down the steps you use in the slice expression:

    1. First, len(numbers) returns the integer 10.
    2. Next, 10 // 2 returns the integer 5 as you use the integer division operator.
    3. Finally, 0:5 is a slice that represents the first five items, which have indices 0 to 4. Note that the endpoint is excluded.

    In the next assignment, where you define second_half, you use the same expression in the slice. However, in this case, the integer 5 represents the start of the range. The slice is now 5: to represent the items from index 5 up to the end of the list.

    If your original list contains an odd number of items, then half of its length will no longer be a whole number. When you use integer division, you obtain the floor of the number. The list first_half will now contain one less item than second_half.

    You can try this out by creating an initial list of eleven numbers instead of ten. The resulting lists will no longer be halves, but they’ll represent the closest alternative to splitting an odd sequence.

    Using the len() Function With Third-Party Libraries

    You can also use Python’s len() with several custom data types from third-party libraries. In the last section of this tutorial, you’ll learn how the behavior of len() depends on the class definition. In this section, you’ll look at examples of using len() with data types from two popular third-party libraries.

    NumPy’s ndarray

    The NumPy module is the cornerstone of all quantitative applications of programming in Python. The module introduces the numpy.ndarray data type. This data type, along with functions within NumPy, is ideally suited for numerical computations and is the building block for data types in other modules.

    Before you can start using NumPy, you’ll need to install the library. You can use Python’s standard package manager, pip, and run the following command in the console:

    $ python -m pip install numpy
    

    You’ve installed NumPy, and now you can create a NumPy array from a list and use len() on the array:

    >>>

    >>> import numpy as np
    
    >>> numbers = np.array([4, 7, 9, 23, 10, 6])
    >>> type(numbers)
    <class 'numpy.ndarray'>
    
    >>> len(numbers)
    6
    

    The NumPy function np.array() creates an object of type numpy.ndarray from the list you pass as an argument.

    However, NumPy arrays can have more than one dimension. You can create a two-dimensional array by converting a list of lists into an array:

    >>>

    >>> import numpy as np
    
    >>> numbers = [
        [11, 1, 10, 10, 15],
        [14, 9, 16, 4, 4],
    ]
    
    >>> numbers_array = np.array(numbers)
    >>> numbers_array
    array([[11,  1, 10, 10, 15],
           [14,  9, 16,  4,  4]])
    
    >>> len(numbers_array)
    2
    
    >>> numbers_array.shape
    (2, 5)
    
    >>> len(numbers_array.shape)
    2
    
    >>> numbers_array.ndim
    2
    

    The list numbers consists of two lists, each containing five integers. When you use this list of lists to create a NumPy array, the result is an array with two rows and five columns. The function returns the number of rows in the array when you pass this two-dimensional array as an argument in len().

    To get the size of both dimensions, you use the property .shape, which is a tuple showing the number of rows and columns. You obtain the number of dimensions of a NumPy array either by using .shape and len() or by using the property .ndim.

    In general, when you have an array with any number of dimensions, len() returns the size of the first dimension:

    >>>

    >>> import numpy as np
    
    >>> array_3d = np.random.randint(1, 20, [2, 3, 4])
    >>> array_3d
    array([[[14,  9, 15, 14],
            [17, 11, 10,  5],
            [18,  1,  3, 12]],
           [[ 1,  5,  6, 10],
            [ 6,  3,  1, 12],
            [ 1,  4,  4, 17]]])
    
    >>> array_3d.shape
    (2, 3, 4)
    
    >>> len(array_3d)
    2
    

    In this example, you create a three-dimensional array with the shape (2, 3, 4) where each element is a random integer between 1 and 20. You use the function np.random.randint() to create an array this time. The function len() returns 2, which is the size of the first dimension.

    Check out NumPy Tutorial: Your First Steps Into Data Science in Python to learn more about using NumPy arrays.

    Pandas’ DataFrame

    The DataFrame type in the pandas library is another data type that is used extensively in many applications.

    Before you can use pandas, you’ll need to install it by using the following command in the console:

    $ python -m pip install pandas
    

    You’ve installed the pandas package, and now you can create a DataFrame from a dictionary:

    >>>

    >>> import pandas as pd
    
    >>> marks = {
        "Robert": [60, 75, 90],
        "Mary": [78, 55, 87],
        "Kate": [47, 96, 85],
        "John": [68, 88, 69],
    }
    
    >>> marks_df = pd.DataFrame(marks, index=["Physics", "Math", "English"])
    
    >>> marks_df
             Robert  Mary  Kate  John
    Physics      60    78    47    68
    Math         75    55    96    88
    English      90    87    85    69
    
    >>> len(marks_df)
    3
    
    >>> marks_df.shape
    (3, 4)
    

    The dictionary’s keys are strings representing the names of students in a class. The value of each key is a list with the marks for three subjects. When you create a DataFrame from this dictionary, you define the index using a list containing the subject names.

    The DataFrame has three rows and four columns. The function len() returns the number of rows in the DataFrame. The DataFrame type also has a .shape property, which you can use to show that the first dimension of a DataFrame represents the number of rows.

    You’ve seen how len() works with a number of built-in data types and also with some data types from third-party modules. In the following section, you’ll learn how to define any class so that it’s usable as an argument for the len() Python function.

    You can explore the pandas module further in The Pandas DataFrame: Make Working With Data Delightful.

    Using len() on User-Defined Classes

    When you define a class, one of the special methods you can define is .__len__(). These special methods are called dunder methods as they have double underscores at the beginning and end of the method names. Python’s built-in len() function calls its argument’s .__len__() method.

    In the previous section, you’ve seen how len() behaves when the argument is a pandas DataFrame object. This behavior is determined by the .__len__() method for the DataFrame class, which you can see in the module’s source code in pandas.core.frame:

    class DataFrame(NDFrame, OpsMixin):
        # ...
        def __len__(self) -> int:
            """
            Returns length of info axis, but here we use the index.
            """
            return len(self.index)
    

    This method returns the length of the DataFrame’s .index property using len(). This dunder method defines the length of a DataFrame to be equal to the number of rows in the DataFrame as represented by .index.

    You can explore the .__len__() dunder method further with the following toy example. You’ll define a class named YString. This data type is based on the built-in string class, but objects of type YString give the letter Y more importance than all the other letters:

    # ystring.py
    
    class YString(str):
        def __init__(self, text):
            super().__init__()
    
        def __str__(self):
            """Display string as lowercase except for Ys that are uppercase"""
            return self.lower().replace("y", "Y")
    
        def __len__(self):
            """Returns the number of Ys in the string"""
            return self.lower().count("y")
    

    The .__init__() method of YString initializes the object using the .__init__() method of the parent str class. You achieve this using the function super(). The .__str__() method defines the way the object is displayed. The functions str(), print(), and format() all call this method. For this class, you represent the object as an all-lowercase string with the exception of the letter Y, which you display as uppercase.

    For this toy class, you define the object’s length as the number of occurrences of the letter Y in the string. Therefore, the .__len__() method returns the count of the letter Y.

    You can create an object of class YString and find its length. The module name used for the example above is ystring.py:

    >>>

    >>> from ystring import YString
    
    >>> message = YString("Real Python? Yes! Start reading today to learn Python")
    
    >>> print(message)
    real pYthon? Yes! start reading todaY to learn pYthon
    
    >>> len(message)  # Returns number of Ys in message
    4
    

    You create an object of type YString from an object of type str and show the representation of the object using print(). You then use the object message as an argument for len(). This calls the class’s .__len__() method, and the result is the number of occurrences of the letter Y in message. In this case, the letter Y appears four times.

    The YString class is not a very useful one, but it helps illustrate how you can customize the behavior of len() to suit your needs. The .__len__() method must return a non-negative integer. Otherwise, it raises an error.

    Another special method is the .__bool__() method, which determines how an object can be converted to a Boolean. The .__bool__() dunder method is not normally defined for sequences and collections. In these cases, the .__len__() method determines the truthiness of an object:

    >>>

    >>> from ystring import YString
    
    >>> first_test = "tomorrow"
    >>> second_test = "today"
    
    >>> bool(first_test)
    True
    
    >>> bool(YString(first_test))
    False
    
    >>> bool(second_test)
    True
    
    >>> bool(YString(second_test))
    True
    

    The variable first_string doesn’t have a Y in it. As shown by the output from bool(), the string is truthy as it’s non-empty. However, when you create an object of type YString from this string, the new object is falsy as there are no Y letters in the string. Therefore, len() returns 0. In contrast, the variable second_string does include the letter Y, and so both the string and the object of type YString are truthy.

    You can read more about using object-oriented programming and defining classes in Object-Oriented Programming (OOP) in Python 3.

    Conclusion

    You’ve explored how to use len() to determine the number of items in sequences, collections, and other data types that hold several items at a time, such as NumPy arrays and pandas DataFrames.

    The len() Python function is a key tool in many programs. Some of its uses are straightforward, but there’s a lot more to this function than its most basic use cases, as you’ve seen in this tutorial. Knowing when you can use this function and how to use it effectively will help you write neater code.

    In this tutorial, you’ve learned how to:

    • Find the length of built-in data types using len()
    • Use len() with third-party data types
    • Provide support for len() with user-defined classes

    You now have a good foundation for understanding the len() function. Learning more about len() helps you understand the differences between data types better. You’re ready to use len() in your algorithms and to improve the functionality of some of your class definitions by enhancing them with the .__len__() method.

    Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python’s len() Function

    Текстовые переменные str в Питоне

    Строковый тип str в Python используют для работы с любыми текстовыми данными. Python автоматически определяет тип str по кавычкам – одинарным или двойным:

            >>> stroka = 'Python'
    >>> type(stroka)
    <class 'str'>
    >>> stroka2 = "code"
    >>> type(stroka2)
    <class 'str'>
    
        

    Для решения многих задач строковую переменную нужно объявить заранее, до начала исполнения основной части программы. Создать пустую переменную str просто:

            stroka = ''
        

    Или:

            stroka2 = ""
        

    Если в самой строке нужно использовать кавычки – например, для названия книги – то один вид кавычек используют для строки, второй – для выделения названия:

            >>> print("'Самоучитель Python' - возможно, лучший справочник по Питону.")
    'Самоучитель Python' - возможно, лучший справочник по Питону.
    >>> print('"Самоучитель Python" - возможно, лучший справочник по Питону.')
    "Самоучитель Python" - возможно, лучший справочник по Питону.
    
        

    Использование одного и того же вида кавычек внутри и снаружи строки вызовет ошибку:

            >>> print(""Самоучитель Python" - возможно, лучший справочник по Питону.")
      File "<pyshell>", line 1
        print(""Самоучитель Python" - возможно, лучший справочник по Питону.")
                          ^
    SyntaxError: invalid syntax
    
        

    Кроме двойных " и одинарных кавычек ', в Python используются и тройные ''' – в них заключают текст, состоящий из нескольких строк, или программный код:

            >>> print('''В тройные кавычки заключают многострочный текст.
    Программный код также можно выделить тройными кавычками.''')
    В тройные кавычки заключают многострочный текст.
    Программный код также можно выделить тройными кавычками.
    
        

    Длина строки len в Python

    Для определения длины строки используется встроенная функция len(). Она подсчитывает общее количество символов в строке, включая пробелы:

            >>> stroka = 'python'
    >>> print(len(stroka))
    6
    >>> stroka1 = ' '
    >>> print(len(stroka1))
    1
    
        

    Преобразование других типов данных в строку

    Целые и вещественные числа преобразуются в строки одинаково:

            >>> number1 = 55
    >>> number2 = 55.5
    >>> stroka1 = str(number1)
    >>> stroka2 = str(number2)
    >>> print(type(stroka1))
    <class 'str'>
    >>> print(type(stroka2))
    <class 'str'>
    
        

    Решение многих задач значительно упрощается, если работать с числами в строковом формате. Особенно это касается заданий, где нужно разделять числа на разряды – сотни, десятки и единицы.

    Сложение и умножение строк

    Как уже упоминалось в предыдущей главе, строки можно складывать – эта операция также известна как конкатенация:

            >>> str1 = 'Python'
    >>> str2 = ' - '
    >>> str3 = 'самый гибкий язык программирования'
    >>> print(str1 + str2 + str3)
    Python - самый гибкий язык программирования
    
        

    При необходимости строку можно умножить на целое число – эта операция называется репликацией:

            >>> stroka = '*** '
    >>> print(stroka * 5)
    *** *** *** *** ***
    
        

    Подстроки

    Подстрокой называется фрагмент определенной строки. Например, ‘abra’ является подстрокой ‘abrakadabra’. Чтобы определить, входит ли какая-то определенная подстрока в строку, используют оператор in:

            >>> stroka = 'abrakadabra'
    >>> print('abra' in stroka)
    True
    >>> print('zebra' in stroka)
    False
    
        

    Для обращения к определенному символу строки используют индекс – порядковый номер элемента. Python поддерживает два типа индексации – положительную, при которой отсчет элементов начинается с 0 и с начала строки, и отрицательную, при которой отсчет начинается с -1 и с конца:

    Положительные индексы 0 1 2 3 4 5 6
    Пример строки P r o g l i b
    Отрицательные индексы -7 -6 -5 -4 -3 -2 -1

    Чтобы получить определенный элемент строки, нужно указать его индекс в квадратных скобках:

            >>> stroka = 'программирование'
    >>> print(stroka[7])
    м
    >>> print(stroka[-1])
    е
    
        

    Срезы строк в Python

    Индексы позволяют работать с отдельными элементами строк. Для работы с подстроками используют срезы, в которых задается нужный диапазон:

            >>> stroka = 'программирование'
    >>> print(stroka[7:10])
    мир
    
        

    Диапазон среза [a:b] начинается с первого указанного элемента а включительно, и заканчивается на последнем, не включая b в результат:

            >>> stroka = 'программa'
    >>> print(stroka[3:8])
    грамм
        

    Если не указать первый элемент диапазона [:b], срез будет выполнен с начала строки до позиции второго элемента b:

            >>> stroka = 'программa'
    >>> print(stroka[:4])
    прог
    
        

    В случае отсутствия второго элемента [a:] срез будет сделан с позиции первого символа и до конца строки:

            >>> stroka = 'программa'
    >>> print(stroka[3:])
    граммa
    
        

    Если не указана ни стартовая, ни финальная позиция среза, он будет равен исходной строке:

            >>> stroka = 'позиции не заданы'
    >>> print(stroka[:])
    позиции не заданы
    
        

    Шаг среза

    Помимо диапазона, можно задавать шаг среза. В приведенном ниже примере выбирается символ из стартовой позиции среза, а затем каждая 3-я буква из диапазона:

            >>> stroka = 'Python лучше всего подходит для новичков.'
    >>> print(stroka[1:15:3])
    yoлшв
    
        

    Шаг может быть отрицательным – в этом случае символы будут выбираться, начиная с конца строки:

            >>> stroka = 'это пример отрицательного шага'
    >>> print(stroka[-1:-15:-4])
    а нт
    
        

    Срез [::-1] может оказаться очень полезным при решении задач, связанных с палиндромами:

            >>> stroka = 'А роза упала на лапу Азора'
    >>> print(stroka[::-1])
    арозА упал ан алапу азор А
    
        

    Замена символа в строке

    Строки в Python относятся к неизменяемым типам данных. По этой причине попытка замены символа по индексу обречена на провал:

            >>> stroka = 'mall'
    >>> stroka[0] = 'b'
    Traceback (most recent call last):
      File "<pyshell>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    
        

    Но заменить любой символ все-таки можно – для этого придется воспользоваться срезами и конкатенацией. Результатом станет новая строка:

            >>> stroka = 'mall'
    >>> stroka = 'b' + stroka[1:]
    >>> print(stroka)
    ball
    
        

    Более простой способ «замены» символа или подстроки – использование метода replace(), который мы рассмотрим ниже.

    Полезные методы строк

    Python предоставляет множество методов для работы с текстовыми данными. Все методы можно сгруппировать в четыре категории:

    • Преобразование строк.
    • Оценка и классификация строк.
    • Конвертация регистра.
    • Поиск, подсчет и замена символов.

    Рассмотрим эти методы подробнее.

    Преобразование строк

    Три самых используемых метода из этой группы – join(), split() и partition(). Метод join() незаменим, если нужно преобразовать список или кортеж в строку:

            >>> spisok = ['Я', 'изучаю', 'Python']
    >>> stroka = ' '.join(spisok)
    >>> print(stroka)
    Я изучаю Python
    
        

    При объединении списка или кортежа в строку можно использовать любые разделители:

            >>> kort = ('Я', 'изучаю', 'Django')
    >>> stroka = '***'.join(kort)
    >>> print(stroka)
    Я***изучаю***Django
    
        

    Метод split() используется для обратной манипуляции – преобразования строки в список:

            >>> text = 'это пример текста для преобразования в список'
    >>> spisok = text.split()
    >>> print(spisok)
    ['это', 'пример', 'текста', 'для', 'преобразования', 'в', 'список']
    
        

    По умолчанию split() разбивает строку по пробелам. Но можно указать любой другой символ – и на практике это часто требуется:

            >>> text = 'цвет: синий; вес: 1 кг; размер: 30х30х50; материал: картон'
    >>> spisok = text.split(';')
    >>> print(spisok)
    ['цвет: синий', ' вес: 1 кг', ' размер: 30х30х50', ' материал: картон']
    
        

    Метод partition() поможет преобразовать строку в кортеж:

            >>> text = 'Python - простой и понятный язык'
    >>> kort = text.partition('и')
    >>> print(kort)
    ('Python - простой ', 'и', ' понятный язык')
    
        

    В отличие от split(), partition() учитывает только первое вхождение элемента-разделителя (и добавляет его в итоговый кортеж).

    Оценка и классификация строк

    В Python много встроенных методов для оценки и классификации текстовых данных. Некоторые из этих методов работают только со строками, в то время как другие универсальны. К последним относятся, например, функции min() и max():

            >>> text = '12345'
    >>> print(min(text))
    1
    >>> print(max(text))
    5
    
    
        

    В Python есть специальные методы для определения типа символов. Например, isalnum() оценивает, состоит ли строка из букв и цифр, либо в ней есть какие-то другие символы:

            >>> text = 'abracadabra123456'
    >>> print(text.isalnum())
    True
    >>> text1 = 'a*b$ra cadabra'
    >>> print(text1.isalnum())
    False
    
        

    Метод isalpha() поможет определить, состоит ли строка только из букв, или включает специальные символы, пробелы и цифры:

            >>> text = 'программирование'
    >>> print(text.isalpha())
    True
    >>> text2 = 'password123'
    >>> print(text2.isalpha())
    False
    
        

    С помощью метода isdigit() можно определить, входят ли в строку только цифры, или там есть и другие символы:

            >>> text = '1234567890'
    >>> print(text.isdigit())
    True
    >>> text2 = '123456789o'
    >>> print(text2.isdigit())
    False
    
        

    Поскольку вещественные числа содержат точку, а отрицательные – знак минуса, выявить их этим методом не получится:

            >>> text = '5.55'
    >>> print(text.isdigit())
    False
    >>> text1 = '-5'
    >>> print(text1.isdigit())
    False
        

    Если нужно определить наличие в строке дробей или римских цифр, подойдет метод isnumeric():

            >>> text = '½⅓¼⅕⅙'
    >>> print(text.isdigit())
    False
    >>> print(text.isnumeric())
    True
    
        

    Методы islower() и isupper() определяют регистр, в котором находятся буквы. Эти методы игнорируют небуквенные символы:

            >>> text = 'abracadabra'
    >>> print(text.islower())
    True
    >>> text2 = 'Python bytes'
    >>> print(text2.islower())
    False
    >>> text3 = 'PYTHON'
    >>> print(text3.isupper())
    True
    
        

    Метод isspace() определяет, состоит ли анализируемая строка из одних пробелов, или содержит что-нибудь еще:

            >>> stroka = '   '
    >>> print(stroka.isspace())
    True
    >>> stroka2 = '  a  '
    >>> print(stroka2.isspace())
    False
    
        

    Конвертация регистра

    Как уже говорилось выше, строки относятся к неизменяемым типам данных, поэтому результатом любых манипуляций, связанных с преобразованием регистра или удалением (заменой) символов будет новая строка.

    Из всех методов, связанных с конвертацией регистра, наиболее часто используются на практике два – lower() и upper(). Они преобразуют все символы в нижний и верхний регистр соответственно:

            >>> text = 'этот текст надо написать заглавными буквами'
    >>> print(text.upper())
    ЭТОТ ТЕКСТ НАДО НАПИСАТЬ ЗАГЛАВНЫМИ БУКВАМИ
    >>> text = 'зДесь ВСе букВы рАзныЕ, а НУжнЫ проПИСНыЕ'
    >>> print(text.lower())
    здесь все буквы разные, а нужны прописные
    
        

    Иногда требуется преобразовать текст так, чтобы с заглавной буквы начиналось только первое слово предложения:

            >>> text = 'предложение должно начинаться с ЗАГЛАВНОЙ буквы.'
    >>> print(text.capitalize())
    Предложение должно начинаться с заглавной буквы.
    
        

    Методы swapcase() и title() используются реже. Первый заменяет исходный регистр на противоположный, а второй – начинает каждое слово с заглавной буквы:

            >>> text = 'пРИМЕР иСПОЛЬЗОВАНИЯ swapcase'
    >>> print(text.swapcase())
    Пример Использования SWAPCASE
    >>> text2 = 'тот случай, когда нужен метод title'
    >>> print(text2.title())
    Тот Случай, Когда Нужен Метод Title
    
        

    Поиск, подсчет и замена символов

    Методы find() и rfind() возвращают индекс стартовой позиции искомой подстроки. Оба метода учитывают только первое вхождение подстроки. Разница между ними заключается в том, что find() ищет первое вхождение подстроки с начала текста, а rfind() с конца:

            >>> text = 'пример текста, в котором нужно найти текстовую подстроку'
    >>> print(text.find('текст'))
    7
    >>> print(text.rfind('текст'))
    37
    
        

    Такие же результаты можно получить при использовании методов index() и rindex() – правда, придется предусмотреть обработку ошибок, если искомая подстрока не будет обнаружена:

            >>> text = 'Съешь еще этих мягких французских булок!'
    >>> print(text.index('еще'))
    6
    >>> print(text.rindex('чаю'))
    Traceback (most recent call last):
      File "<pyshell>", line 1, in <module>
    ValueError: substring not found
    
        

    Если нужно определить, начинается ли строка с определенной подстроки, поможет метод startswith():

            >>> text = 'Жила-была курочка Ряба'
    >>> print(text.startswith('Жила'))
    True
    
        

    Чтобы проверить, заканчивается ли строка на нужное окончание, используют endswith():

            >>> text = 'В конце всех ждал хэппи-енд'
    >>> print(text.endswith('енд'))
    True
    
        

    Для подсчета числа вхождений определенного символа или подстроки применяют метод count() – он помогает подсчитать как общее число вхождений в тексте, так и вхождения в указанном диапазоне:

            >>> text = 'Съешь еще этих мягких французских булок, да выпей же чаю!'
    >>> print(text.count('е'))
    5
    >>> print(text.count('е', 5, 25))
    2
    
        

    Методы strip(), lstrip() и rstrip() предназначены для удаления пробелов. Метод strip() удаляет пробелы в начале и конце строки, lstrip() – только слева, rstrip() – только справа:

            >>> text = '    здесь есть пробелы и слева, и справа    '
    >>> print('***', text.strip(), '***')
    *** здесь есть пробелы и слева, и справа ***
    >>> print('***', text.lstrip(), '***')
    *** здесь есть пробелы и слева, и справа     ***
    >>> print('***', text.rstrip(), '***')
    ***     здесь есть пробелы и слева, и справа ***
        

    Метод replace() используют для замены символов или подстрок. Можно указать нужное количество замен, а сам символ можно заменить на пустую подстроку – проще говоря, удалить:

            >>> text = 'В этой строчке нужно заменить только одну "ч"'
    >>> print(text.replace('ч', '', 1))
    В этой строке нужно заменить только одну "ч"
    
        

    Стоит заметить, что метод replace() подходит лишь для самых простых вариантов замены и удаления подстрок. В более сложных случаях необходимо использование регулярных выражений, которые мы будем изучать позже.

    Практика

    Задание 1

    Напишите программу, которая получает на вход строку и выводит:

    • количество символов, содержащихся в тексте;
    • True или False в зависимости от того, являются ли все символы буквами и цифрами.

    Решение:

            text = input()
    print(len(text))
    print(text.isalpha())
    
        

    Задание 2

    Напишите программу, которая получает на вход слово и выводит True, если слово является палиндромом, или False в противном случае. Примечание: для сравнения в Python используется оператор ==.

    Решение:

            text = input().lower()
    print(text == text[::-1])
    
        

    Задание 3

    Напишите программу, которая получает строку с именем, отчеством и фамилией, написанными в произвольном регистре, и выводит данные в правильном формате. Например, строка алеКСандр СЕРГЕЕВИЧ ПушкиН должна быть преобразована в Александр Сергеевич Пушкин.

    Решение:

            text = input()
    print(text.title())
    
        

    Задание 4

    Имеется строка 12361573928167047230472012. Напишите программу, которая преобразует строку в текст один236один573928один670472304720один2.

    Решение:

            text = '12361573928167047230472012'
    print(text.replace('1', 'один'))
    
        

    Задание 5

    Напишите программу, которая последовательно получает на вход имя, отчество, фамилию и должность сотрудника, а затем преобразует имя и отчество в инициалы, добавляя должность после запятой.

    Пример ввода:

            Алексей
    Константинович
    Романов
    бухгалтер
    
        

    Вывод:

            А. К. Романов, бухгалтер
        

    Решение:

            first_name, patronymic, last_name, position = input(), input(), input(), input()
    print(first_name[0] + '.', patronymic[0] + '.', last_name + ',', position)
    
        

    Задание 6

    Напишите программу, которая получает на вход строку текста и букву, а затем определяет, встречается ли данная буква (в любом регистре) в тексте. В качестве ответа программа должна выводить True или False.

    Пример ввода:

            ЗонтИК
    к
    
        

    Вывод:

            True
        

    Решение:

            text = input().lower()
    letter = input()
    print(letter in text)
    
        

    Задание 7

    Напишите программу, которая определяет, является ли введенная пользователем буква гласной. В качестве ответа программы выводит True или False, буквы могут быть как в верхнем, так и в нижнем регистре.

    Решение:

            vowels = 'аиеёоуыэюя'
    letter = input().lower()
    print(letter in vowels)
    
        

    Задание 8

    Напишите программу, которая принимает на вход строку текста и подстроку, а затем выводит индексы первого вхождения подстроки с начала и с конца строки (без учета регистра).

    Пример ввода:

            Шесть шустрых мышат в камышах шуршат
    ша
    
        

    Вывод:

            16 33
        

    Решение:

            text, letter = input().lower(), input()
    print(text.find(letter), text.rfind(letter))
    
        

    Задание 9

    Напишите программу для подсчета количества пробелов и непробельных символов в введенной пользователем строке.

    Пример ввода:

            В роще, травы шевеля, мы нащиплем щавеля
        

    Вывод:

            Количество пробелов: 6, количество других символов: 34
        

    Решение:

            text = input()
    nospace = text.replace(' ', '')
    print(f"Количество пробелов: {text.count(' ')}, количество других символов: {len(nospace)}")
    
        

    Задание 10

    Напишите программу, которая принимает строку и две подстроки start и end, а затем определяет, начинается ли строка с фрагмента start, и заканчивается ли подстрокой end. Регистр не учитывать.

    Пример ввода:

            Программирование на Python - лучшее хобби
    про
    про
    
        

    Вывод:

            True
    False
    
        

    Решение:

            text, start, end = input().lower(), input(), input()
    print(text.startswith(start))
    print(text.endswith(end))
    
        

    Подведем итоги

    В этой части мы рассмотрели самые популярные методы работы со строками – они пригодятся для решения тренировочных задач и в разработке реальных проектов. В следующей статье будем разбирать методы работы со списками.

    ***

    📖 Содержание самоучителя

    1. Особенности, сферы применения, установка, онлайн IDE
    2. Все, что нужно для изучения Python с нуля – книги, сайты, каналы и курсы
    3. Типы данных: преобразование и базовые операции
    4. Методы работы со строками
    5. Методы работы со списками и списковыми включениями
    6. Методы работы со словарями и генераторами словарей
    7. Методы работы с кортежами
    8. Методы работы со множествами
    9. Особенности цикла for
    10. Условный цикл while
    11. Функции с позиционными и именованными аргументами
    12. Анонимные функции
    13. Рекурсивные функции
    14. Функции высшего порядка, замыкания и декораторы
    15. Методы работы с файлами и файловой системой
    16. Регулярные выражения
    17. Основы скрапинга и парсинга
    18. Основы ООП: инкапсуляция и наследование
    19. Основы ООП – абстракция и полиморфизм
    20. Графический интерфейс на Tkinter

    ***

    Материалы по теме

    • ТОП-15 трюков в Python 3, делающих код понятнее и быстрее

    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!

    Понравилась статья? Поделить с друзьями:

    Не пропустите также:

  • Как найти сильных продавцов
  • Как найти шаровую опору
  • Isbn журнала как найти
  • Как найти площадь треуольника
  • Как найти кнопку обзор

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии