Как найти длинну строки

Теги: 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

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.

    Содержание

    1. Методы определения длины строки
    2. 1. Использование метода len()
    3. 2. Определение собственной функции для поиска длины строки

    Методы определения длины строки

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

    1. Использование метода len()

    Рассматривая первый и самый простой метод, len() напрямую возвращает длину переданного строкового объекта, в котором он вызывается. Метод len() также работает с другими повторяемыми объектами, такими как списки. Приведенный ниже код иллюстрирует, как мы можем использовать эту функцию, а также как она работает.

    #Given string whose length is to be found
    str1="Python is great!"
    print("The given String is:",str1)
    
    #calling our len() method to calculate
    #the length of str1
    print("Length =",len(str1))
    

    Вывод:

    Использование метода len()

    Где:

    • str1 – заданная строка;
    • Затем мы напрямую вызываем метод len() со строкой и печатаем возвращаемое им значение. Как мы видим, метод дает нам правильную длину для данной строки, str1.

    Теперь, переходя к следующей технике, мы можем определить нашу собственную функцию (str_len() в нашем случае) для вычисления длины строки в Python.

    Давайте посмотрим, как мы можем это сделать:

    #function that calculates length of the passed string
    def str_len(str1):
        c=0    #counter initialised as 0
        for i in str1:
            c=c+1   #counter increased for each element
        return c
    
    #Given string whose length is to be found
    str1="JournalDev"
    print("The given String is:",str1)
    
    #calling our str_len() function to calculate
    #the length of str1
    print("Length =",str_len(str1))
    

    Вывод:

    Определение собственной функции для поиска длины строки

    В приведенном выше коде:

    • Мы определяем функцию str_len(), которая принимает строку и возвращает ее длину.
    • Внутри функции мы инициализируем счетчик c = 0, который фактически подсчитывает количество элементов в переданной строке. Мы перебираем строку и продолжаем увеличивать счетчик. Следовательно, к концу цикла for c содержит длину строки. Затем мы возвращаем c.
    • Чтобы проверить, работает ли наша функция должным образом, мы вычисляем и печатаем длину строки str1. Из вывода видно, что функция возвращает значение 9, которое является желаемым выводом.

    ( 1 оценка, среднее 5 из 5 )

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

    Improve Article

    Save Article

    Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type.

    Important Points

    1. The constructor of the String class will set it to the C++ style string, which ends at the ‘.
    2. The size() function is consistent with other STL containers (like vector, map, etc.) and length() is consistent with most people’s intuitive notion of character strings like a word, sentence, or paragraph. We say a paragraph’s length, not its size, so length() is to make things more readable.

    Methods to find the length of string

    1. Using string::size: The method string::size returns the length of the string, in terms of bytes.
    2. Using string::length: The method string::length returns the length of the string, in terms of bytes.  Both string::size and string::length are synonyms and return the exact same value.
    3. Using the C library function strlen() method: The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character.
    4. Using while loop: Using the traditional method, initialize the counter equals 0 and increment the counter from starting of the string to the end of the string (terminating null character).
    5. Using for loop: To initialize the counter equals 0 and increment the counter from starting of the string to the end of the string (terminating null character).

    Examples:

    Input: "Geeksforgeeks"
    Output: 13
    
    Input: "Geeksforgeeks  345"
    Output: 14

    Example:

    C++

    #include <iostream>

    #include <string.h>

    using namespace std;

    int main()

    {

        string str = "GeeksforGeeks";

        cout << str.size() << endl;

        cout << str.length() << endl;

        cout << strlen(str.c_str()) << endl;

        int i = 0;

        while (str[i])

            i++;

        cout << i << endl;

        for (i = 0; str[i]; i++)

            ;

        cout << i << endl;

        return 0;

    }

    Time complexity:
    For all the methods, the time complexity is O(n) as we need to traverse the entire string to find its length.

    Space complexity:
    For all the methods, the space complexity is O(1) as no extra space is required.

    Last Updated :
    10 Mar, 2023

    Like Article

    Save Article

    Overview

    In C, a string is an array of characters that is terminated with a null character «». The length of a string will be determined by counting all the characters in the string (except for the null character).

    Scope of Article

    • In this article, we will learn to find the length of a String in C.
    • All the methods to find the length of a String will be explained in this article.
    • Every method will be explained using syntax, images, and examples.

    Introduction

    The string length in C is equal to the count of all the characters in it (except the null character «»).

    String length in C

    For Example, the string «gfddf» has a length of 5 and the string «4343» has a length of 4.

    Note:
    In C, a String is an array of characters that is terminated with a null character «» to indicate the end of the string.

    How to Find the String Length in C?

    We can find the length of a String by counting all the characters in it (before the null character) using a for loop. We can also use the built-in string.h library function strlen() or the sizeof() operator.
    Let us understand how to use these methods in the coming sections.

    String Length in C using a User-Defined Function

    We can find the length of a string using a user-defined function by iterating over the string in a for loop and incrementing the count of characters (length) by 1 till it reaches the null character «» and then returning the count.

    Let’s take a look at its implementation:
    Code

    // finding the length of a string using a user-defined function
    
    #include <stdio.h>
    
    // The User-defined method
    int str_length(char str[]) {
        // initializing count variable (stores the length of the string)
        int count; 
        
        // incrementing the count till the end of the string
        for (count = 0; str[count] != ''; ++count);
        
        // returning the character count of the string
        return count; 
    }
    
    // Driver code
    int main() {
        // initializing the array to store string characters
        char str[1000]; 
     
        // inputting the string
        printf("Enter the string: ");
        scanf("%s", str); 
        
        // assigning the count of characters in the string to the length of the string
        int length = str_length(str); 
        
        //  printing the length of string
        printf("The length of the string is %d", length); 
     
        return 0;
    }
    

    Output

    Enter the string: 567lens
    The length of the string is 7
    

    Explanation:

    In the above example, we are finding the length of a string by iterating over it in a for loop and incrementing the count by 1 in each iteration till it reaches the null character. The value of count after the end of the for loop will be equal to the length of the string.

    String Length in C Using Built-In Library Function

    The length of a string can be found using the built-in library function strlen() in string.h header file. It returns the length of the string passed to it (ignoring the null character).

    String Length in C using Built-In Library

    Syntax

    
    

    The string is passed to the strlen() function, which returns its length.

    Let us take a look at its implementation.
    Code

    
    // finding the length of a string using the strlen() function from the string.h library
    
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[1000]; // initializing the array to store string characters
     
        // inputting the string
        printf("Enter the string: ");
        scanf("%s", str); 
        
        // initializing the length variable
        int length;
        
        // Using the strlen() function to return the length of the string and assign it to the length variable
        length = strlen(str); 
        
        // printing the length of string
        printf("The length of the string is %d", length); 
     
        return 0;
    }
    

    Output :

    Enter the string: 5654dds
    The length of the string is 7
    

    In the above example, we are finding the length of a string by using the string.h library function strlen(), which returns the length of the string passed to it.

    String Length in C Using the sizeof() Operator

    We can also find the length of a string using the sizeof() Operator in C. The sizeof is a unary operator which returns the size of an entity (variable or value).

    String Length in C using the sizeof Operator

    Syntax

    
    

    The value is written with the sizeof operator which returns its size (in bytes).

    Let us take a look at its implementation:
    Code

    // finding the length of a string using the sizeof operator
    
    #include <stdio.h>
    
    int main() {
        // initializing the string literal
        char str[] = "g4343"; 
        
        // printing the string
        printf("The given string is %sn", str);
        
        // initializing the length variable
        int length;
        
        // using the sizeof operator to find the length of the string
        length = sizeof str; 
        
        // printing the length of string
        printf("The length of the string is %d", length-1); 
     
        return 0;
    }
    

    Output

    The given string is g4343
    The length of the string is 5
    

    In the above example, we are finding the length of the string «g4343» using the sizeof operator in C. The sizeof operator returns its length as 6 in the output as It returns the size of an operand, not the string length (including null values). But here, if we print length-1 then we get the length of the string.

    Conclusion

    • In C, the length of a string is the count of all its characters except the null character «».
    • We can find the length of the string using a for loop by counting each character in each iteration.
    • The built-in library function strlen() is used to return the length of a string passed to it.
    • We can also find the length of a C String using the sizeof operator.

    Понравилась статья? Поделить с друзьями:
  • Как найти конфигурацию системы на виндовс 10
  • Как найти свой бизнес кафе
  • Как найти ссылку на свой канал дзен
  • Как найти все подписки на youtube
  • Как найти по углу часть окружности