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

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

(PHP 4, PHP 5, PHP 7, PHP 8)

strlenВозвращает длину строки

Описание

strlen(string $string): int

Список параметров

string

Строка (string), для которой измеряется длина.

Возвращаемые значения

Функция возвращает длину строки string в байтах.

Примеры

Пример #1 Пример использования strlen()


<?php
$str
= 'abcdef';
echo
strlen($str); // 6$str = ' ab cd ';
echo
strlen($str); // 7
?>

Примечания

Замечание:

Функция strlen() возвратит количество байт, а не число символов
в строке.

Смотрите также

  • count() — Подсчитывает количество элементов массива или Countable объекте
  • grapheme_strlen() — Получает длину строки в единицах графемы
  • iconv_strlen() — Возвращает количество символов в строке
  • mb_strlen() — Получает длину строки

rm dot nasir at hotmail dot com

7 years ago


I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: "strlen() returns the number of bytes rather than the number of characters in a string.", so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().

Example:

<?php
// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = "السلام علیکم ورحمة الله وبرکاته!";var_export( strlen($utf8) ); // 59
echo "<br>";
var_export( mb_strlen($utf8, 'utf8') ); // 32
?>


Daniel Klein

7 months ago


Since PHP 8.0, passing null to strlen() is deprecated. To check for a blank string (not including '0'):

<?php
// PHP < 8.0
if (!strlen($text)) {
  echo
'Blank';
}
// PHP >= 8.0
if ($text === null || $text === '')) {
  echo
'empty';
}


joeri at sebrechts dot net

6 years ago


When checking for length to make sure a value will fit in a database field, be mindful of using the right function.

There are three possible situations:

1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database).

<?php
// ok if php.ini default_charset set to UTF-8 (= default value)
mb_strlen($value);
iconv_strlen($value);
// always ok
mb_strlen($value, "UTF-8");
iconv_strlen($value, "UTF-8");// BAD, do not use:
strlen(utf8_decode($value)); // breaks for some multi-byte characters
grapheme_strlen($value); // counts graphemes, not code points
?>

2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE))

<?php
// ok, but assumes mbstring.func_overload is 0 in php.ini (= default value)
strlen($value);
// ok, forces count in bytes
mb_strlen($value, "8bit")
?>

3. The database column is in another character set (UTF-16, ISO-8859-1, etc...) with a length defined in characters / code points.

Find the character set used, and pass it explicitly to the length function.

<?php
// ok, supported charsets: http://php.net/manual/en/mbstring.supported-encodings.php
mb_strlen($value, $charset);
// ok, supported charsets: https://www.gnu.org/software/libiconv/
iconv_strlen($value, $charset);
?>


jasonrohrer at fastmail dot fm

9 years ago


PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes (''). 

In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.

For example, in PHP:

strlen( "test" ) = 5

In C, the same call would return 2.

Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).


basil at gohar dot us

12 years ago


We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes

= array('one', 'two', 'three');

if (

strlen($attributes) == 0 && !is_bool($attributes)) {
    echo
"We are in the 'if'n"//  PHP 5.3
} else {
    echo
"We are in the 'else'n"//  PHP 5.2
}?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.


vcardillo at gmail dot com

10 years ago


I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?

<?php
$foo
= null;
$len = strlen(null);
$bar = '';

echo

"Length: " . strlen($foo) . "<br>";
echo
"Length: $len <br>";
echo
"Length: " . strlen(null) . "<br>";

if (

strlen($foo) === 0) echo 'Null length is Zero <br>';
if (
$len === 0) echo 'Null length is still Zero <br>';

if (

strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
else echo
'!is_null(): $foo is probably null <br>';

if (

strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
else echo
'isset(): $foo is probably null <br>';

if (

strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
else echo
'!is_null(): $foo is probably null <br>';

if (

strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
else echo
'isset(): $foo is probably null <br>';
?>

// Begin Output:
Length: 0
Length: 0
Length: 0

Null length is Zero
Null length is still Zero

!is_null(): $foo is probably null
isset(): $foo is probably null

!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output

So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.


John

6 years ago


There's a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is "super slow". Well, that was probably true in old versions of PHP. But as of PHP7 that's definitely no longer true. It's now SUPER fast!

I created a 20,00,000 byte string (~20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.

The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn't get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation

So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!

Here is the complete benchmark code if you want to reproduce it on your machine:

<?php

$iterations

= 100000000; // 100 million
$str = str_repeat( '0', 20000000 );// benchmark loop and variable assignment to calculate loop overhead
$start = microtime(true);
for(
$i = 0; $i < $iterations; ++$i ) {
   
$len = 0;
}
$end = microtime(true);
$loop_elapsed = 1000 * ($end - $start);// benchmark strlen in a loop
$len = 0;
$start = microtime(true);
for(
$i = 0; $i < $iterations; ++$i ) {
   
$len = strlen( $str );
}
$end = microtime(true);
$strlen_elapsed = 1000 * ($end - $start);// subtract loop overhead from strlen() speed calculation
$strlen_elapsed -= $loop_elapsed;

echo

"nstring length: {$len}ntest took: {$strlen_elapsed} millisecondsn";?>


Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Python len() function returns the length of the string. 

    Python len() Syntax

    Syntax: len(string) 

    Return: It returns an integer which is the length of the string. 

    Python len() Example

    len() methods with string in Python.

    Python3

    string = "Geeksforgeeks"

    print(len(string))

    Output:

    13

    Example 1: Len() function with tuples and string

    Here we are counting length of the tuples and list.

    Python

    tup = (1,2,3)

    print(len(tup))

    l = [1,2,3,4]

    print(len(l))

    Output: 

    3
    4

    Example 2: Python len() TypeError

    Python3

    Output:

    TypeError: object of type 'bool' has no len()

    Example 3: Python len() with dictionaries and sets

    Python3

    dic = {'a':1, 'b': 2}

    print(len(dic))

    s = { 1, 2, 3, 4}

    print(len(s))

    Output:

    2
    4

    Example 4: Python len() with custom objects

    Python3

    class Public:

        def __init__(self, number):

            self.number = number

        def __len__(self):

            return self.number

    obj = Public(12)

    print(len(obj))

    Output:

    12

    Time complexity : 

    len() function  has time complexity of O(1). in average and amortized case

    Last Updated :
    11 Jan, 2023

    Like Article

    Save Article

    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

    На чтение 6 мин Просмотров 21к. Опубликовано 03.03.2022

    Строка представляет собой массив символов или букв. Это последовательный набор букв или массив символов. Утверждение и описание строки, содержащей набор символов, аналогичны утверждению и определению расположения других типов данных. В C++ длина строки означает количество байтов, которые используются для шифрования указанной строки. Это связано с тем, что байты обычно сопоставляются с символами C++.

    В этой статье мы обсудим различные методы определения длины строки в C++. Мы устанавливаем программное обеспечение «DEVC++» на наш ноутбук для выполнения кодов. Сначала мы создаем новый файл, нажав «Ctrl + N» на клавиатуре. После кодирования компилируем и запускаем код по «F11» с клавиатуры.

    Содержание

    1. Используйте циклы «While» и «For»
    2. Используйте функцию Strlen()
    3. Используйте метод Str.length()
    4. Заключение

    Используйте циклы «While» и «For»

    Использование цикла while подобно традиционному методу определения длины различных строк. При использовании цикла for и while мы устанавливаем переменную «счетчик» на 0, а затем добавляем этот счетчик от начала заданной строки до завершения строки (заканчивается нулевым символом).

    В этом случае мы используем две петли. Цикл for и цикл while могут определять длину определенной строки. Во-первых, мы используем директивы препроцессора. Он содержит заголовочный файл. Это используется в начале программы. Эти директивы начинаются со знака «#»:

    #include<iostream>
    using namespace std;
    int main()
    {
    string str = «visual programming»;
    int i = 0,count=0;
    while (str[i] != )
    {
    ++i;
    }
    cout <<«Length of the string by using While Loop: «<< i << endl;
    for (i=0; str[i]!=; i++)
    {
    count++;
    }
    cout <<«Length of the string by using For Loop: «<< count << endl;
    return 0;
    }

    Здесь мы берем заголовочный файл #include. Затем мы используем основную функцию. Каждая программа на C++ содержит функцию main(), которая является первым сегментом, реализуемым при выполнении кода.

    Теперь возьмем строку «визуальное программирование». Для этой строки используется переменная «str». Далее берем еще две переменные: переменную «i» и переменную «count». Объявляем переменную «i». Здесь мы используем переменную с именем «count», чтобы определить длину строки. Мы инициализируем обе переменные нулем. Здесь мы используем цикл while. Каждая строка заканчивается символом «», и это называется управляющей последовательностью. Этот «» не является отличительным символом. Это точное число ноль. Цикл while выполняется до тех пор, пока переменная «str[i]» не перестанет быть эквивалентной escape-серии.

    В конце цикла значение «I» увеличивается до 0, пока не будет найден последний элемент заданной строки. Таким образом, мы узнаем длину данной строки. Мы используем «cout» для вывода сообщения «длина строки с использованием цикла while»:

    Теперь воспользуемся циклом for

    Теперь воспользуемся циклом for. Здесь выражение «i=0» инициализирует переменную «i» значением 0. Инициализация выполняется сразу после входа в цикл. Этот цикл выполняется до тех пор, пока не будет достигнут последний символ. Выражение «i++» увеличивает переменную «i» каждый раз при выполнении цикла. В цикле переменная count добавляется каждый раз, пока не будет достигнуто окончание определенной строки. Таким образом, мы получаем значение переменной «count» и переменной «i». В конце мы снова используем «cout», чтобы напечатать оператор «длина строки с использованием цикла for».

    Используйте функцию Strlen()

    «Sstring» — это библиотека, содержащая функцию strlen(). В C++ мы используем функцию strlen() для получения длины строки. Это встроенная функция. Он используется в строках в стиле C. Эта встроенная функция возвращает длину определенной строки от первого символа до конечного нулевого символа:

    #include <iostream>
    #include <cstring>
    using namespace std;

    int main() {
    char str[] = “I love to play badminto”«;
    int len = strlen(str);
    cout <<“»
    Length of the string :» << len << endl;
    }

    В этом случае сначала мы используем заголовочный файл «#include ». И мы должны использовать заголовочный файл «#include » в начале программы для выполнения кода, в котором мы используем функцию strlen(). Следующий пример кода получает строку в стиле C и массив символов и использует функцию strlen() для получения ее длины. Берем строку «Я люблю играть в бадминтон», чтобы получить длину этой строки.

    Данная строка содержит 24 символа

    Данная строка содержит 24 символа. Итак, мы получаем 24 вывода. Мы используем «cout» для вывода сообщения «длина строки».

    Используйте метод Str.length()

    Другой метод определения длины заданной строки — использование функции str.length(). Он обеспечивает длину строки в байтах. Это фактическое количество байтов, соответствующих символам строки, а не ее вместимость. Объект определенной строки захватывает байты без шифрования информации, которая может быть использована для шифрования его символов. Таким образом, возвращаемое значение может не отражать реальное количество зашифрованных символов в последовательности многобайтовых символов:

    #include <iostream>
    #include <string>
    int main ()
    {
    std::string str (“modern programming language”);
    std::cout << “The length of the string is “ << str.length();
    return 0;
    }

    Мы используем два заголовочных файла: «#include » и «#include ». Берем объект «str» класса «std::string». Затем мы хотим получить длину строки для «современного языка программирования». Мы используем функцию str.length(). Это встроенная функция. Другой встроенной функцией, используемой для определения длины строки, является str.size(). Использование обеих функций вернет идентичный результат. Эти функции возвращают длину заданной строки в байтах:

    Для строк класса мы всегда используем подходящие методы

    Для строк класса мы всегда используем подходящие методы. Например, мы используем str.length() или str.size(), чтобы найти их длину. Использование std::string обычно проще, поскольку оно автоматически выделяет память.

    Заключение

    В этой статье мы объяснили несколько подходов, которые используются для получения длины различных строк в C++. Строки C++ представляют собой расположение букв или символов, сохраненных в соседних адресах памяти. Чтобы получить длину строк в стиле C, мы используем метод strlen(). В строке конструктор задает строку в стиле C, оканчивающуюся на «». В последнем методе мы используем встроенную функцию str.length(). Этот метод довольно прост в реализации, потому что мы просто вызываем встроенную функцию и получаем длину. Мы надеемся, что вы нашли эту статью полезной. Ознакомьтесь с другими статьями Linux Hint, чтобы получить дополнительные советы и информацию.

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