Python уменьшить длину строки

Строки. Функции и методы строк

Python 3 логотип

Итак, о работе со строками мы немного поговорили, теперь поговорим о функциях и методах строк.

Я постарался собрать здесь все строковые методы и функции, но если я что-то забыл — поправляйте.

Базовые операции

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

  :  Поэтому все строковые методы возвращают новую строку, которую потом следует присвоить переменной.

Таблица «Функции и методы строк»

Функция или метод Назначение
S = ‘str’; S = «str»; S = »’str»’; S = «»»str»»» Литералы строк
S = «s\np\ta\nbbb» Экранированные последовательности
S = r»C:\temp\new» Неформатированные строки (подавляют экранирование)
S = b»byte» Строка байтов
S1 + S2 Конкатенация (сложение строк)
S1 * 3 Повторение строки
S[i] Обращение по индексу
S[i:j:step] Извлечение среза
len(S) Длина строки
S.find(str, [start],[end]) Поиск подстроки в строке. Возвращает номер первого вхождения или -1
S.rfind(str, [start],[end]) Поиск подстроки в строке. Возвращает номер последнего вхождения или -1
S.index(str, [start],[end]) Поиск подстроки в строке. Возвращает номер первого вхождения или вызывает ValueError
S.rindex(str, [start],[end]) Поиск подстроки в строке. Возвращает номер последнего вхождения или вызывает ValueError
S.replace(шаблон, замена[, maxcount]) Замена шаблона на замену. maxcount ограничивает количество замен
S.split(символ) Разбиение строки по разделителю
S.isdigit() Состоит ли строка из цифр
S.isalpha() Состоит ли строка из букв
S.isalnum() Состоит ли строка из цифр или букв
S.islower() Состоит ли строка из символов в нижнем регистре
S.isupper() Состоит ли строка из символов в верхнем регистре
S.isspace() Состоит ли строка из неотображаемых символов (пробел, символ перевода страницы (‘\f’), «новая строка» (‘\n’), «перевод каретки» (‘\r’), «горизонтальная табуляция» (‘\t’) и «вертикальная табуляция» (‘\v’))
S.istitle() Начинаются ли слова в строке с заглавной буквы
S.upper() Преобразование строки к верхнему регистру
S.lower() Преобразование строки к нижнему регистру
S.startswith(str) Начинается ли строка S с шаблона str
S.endswith(str) Заканчивается ли строка S шаблоном str
S.join(список) Сборка строки из списка с разделителем S
ord(символ) Символ в его код ASCII
chr(число) Код ASCII в символ
S.capitalize() Переводит первый символ строки в верхний регистр, а все остальные в нижний
S.center(width, [fill]) Возвращает отцентрованную строку, по краям которой стоит символ fill (пробел по умолчанию)
S.count(str, [start],[end]) Возвращает количество непересекающихся вхождений подстроки в диапазоне [начало, конец] (0 и длина строки по умолчанию)
S.expandtabs([tabsize]) Возвращает копию строки, в которой все символы табуляции заменяются одним или несколькими пробелами, в зависимости от текущего столбца. Если TabSize не указан, размер табуляции полагается равным 8 пробелам
S.lstrip([chars]) Удаление пробельных символов в начале строки
S.rstrip([chars]) Удаление пробельных символов в конце строки
S.strip([chars]) Удаление пробельных символов в начале и в конце строки
S.partition(шаблон) Возвращает кортеж, содержащий часть перед первым шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий саму строку, а затем две пустых строки
S.rpartition(sep) Возвращает кортеж, содержащий часть перед последним шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий две пустых строки, а затем саму строку
S.swapcase() Переводит символы нижнего регистра в верхний, а верхнего – в нижний
S.title() Первую букву каждого слова переводит в верхний регистр, а все остальные в нижний
S.zfill(width) Делает длину строки не меньшей width, по необходимости заполняя первые символы нулями
S.ljust(width, fillchar=» «) Делает длину строки не меньшей width, по необходимости заполняя последние символы символом fillchar
S.rjust(width, fillchar=» «) Делает длину строки не меньшей width, по необходимости заполняя первые символы символом fillchar
S.format(*args, **kwargs) Форматирование строки

Для вставки кода на Python в комментарий заключайте его в теги

Источник

Python уменьшить длину строки

Last updated: Feb 21, 2023
Reading time · 4 min

banner

# Table of Contents

# Truncate a string in Python

Use string slicing to truncate a string, e.g. result = my_str[:5] . The slice returns the first N characters of the string.

Ellipsis can be added to the end of the substring if the string is longer than the slice.

Copied!
my_str = 'bobbyhadz.com' result = my_str[:5] print(result) # 👉️ bobby

We used string slicing to truncate a string.

The syntax for string slicing is my_str[start:stop:step] .

Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) - 1 .

The stop index is exclusive (up to, but not including), so the slice returns the first N characters of the string.

Copied!
my_str = 'bobbyhadz.com' result = my_str[:5] print(result) # 👉️ bobby

The example returns a substring containing the first 5 characters of the string.

# Truncate a string with an ellipsis in Python

You can use the ternary operator to add an ellipsis if the string is longer than the slice.

Copied!
my_str = 'bobbyhadz.com' result = my_str[:5] + '. ' if len(my_str) > 5 else my_str print(result) # 👉️ bobby.

The expression to the left of the if statement is returned if the condition is met, otherwise, the string gets returned as is.

# Creating a reusable function

If you have to do this often, define a reusable function.

Copied!
def truncate_string(string, length, suffix='. '): return string[:length] + suffix print(truncate_string('bobbyhadz.com', 3)) # bob. print(truncate_string('bobbyhadz.com', 5)) # bobby. print(truncate_string('bobbyhadz.com', 7)) # bobbyha.

The function takes a string, the desired length and optionally a suffix as parameters and truncates the given string to the specified length.

# Truncate a string using a formatted string literal

Alternatively, you can use a formatted string literal.

Copied!
my_str = 'bobbyhadz.com' result = f'my_str:.5>' print(result) # 👉️ bobby result = f'my_str:.5>". " if len(my_str) > 5 else "">' print(result) # 👉️ bobby.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Copied!
var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - .

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

Copied!
my_str = 'bobbyhadz.com' result = f'my_str:.5>' print(result) # 👉️ bobby

The digit after the period is the maximum size of the string.

The example formats the string to a maximum of 5 characters.

You can use the ternary operator to add an ellipsis if the string is longer than the slice.

Copied!
my_str = 'bobbyhadz.com' result = f'my_str:.5>". " if len(my_str) > 5 else "">' print(result) # 👉️ bobby.

# Truncate a string using str.rsplit()

If you need to remove the last word from a string, use the str.rsplit() method.

Copied!
my_str = 'bobby hadz com' new_str = my_str.rsplit(' ', 1)[0] print(new_str) # 👉️ 'bobby hadz'

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

Copied!
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

The method takes the following 2 arguments:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done, the rightmost ones (optional)

If you need to remove the last 2 words from a string, set the maxsplit argument to 2 and access the list item at index 0 .

Copied!
my_str = 'bobby hadz com' # 👇️ remove last word from string result = my_str.rsplit(' ', 1)[0] print(result) # 👉️ bobby hadz # 👇️ remove last 2 words from string result = my_str.rsplit(' ', 2)[0] print(result) # 👉️ bobby

The maxsplit argument can be set to split the string at most N times from the right.

# Truncate a string using textwrap.shorten()

You can also use the textwrap.shorten() method to truncate a string.

Copied!
import textwrap a_string = 'bobby hadz com one two three' new_string = textwrap.shorten(a_string, width=8, placeholder='') print(new_string) # 👉️ bobby new_string = textwrap.shorten(a_string, width=8, placeholder='. ') print(new_string) # 👉️ bobby. new_string = textwrap.shorten(a_string, width=15, placeholder='. ') print(new_string) # 👉️ bobby hadz.

The textwrap.shorten method takes a string, the max width of the string and a placeholder as parameter and truncates the string.

The method collapses and truncates the string to fit in the given width.

Note that the placeholder is included in the width of the string.

Copied!
import textwrap a_string = 'bobby hadz com one two three' new_string = textwrap.shorten(a_string, width=5, placeholder='. ') print(new_string) # 👉️ .

The first word + the placeholder exceeds the specified max width of 5 , so only the placeholder is returned.

The textwrap.shorten() method:

  1. Collapses the whitespace (replaces multiple, consecutive spaces with a single space).
  2. If the result fits in the specified width, it is returned.
  3. Otherwise, enough words are dropped from the end of the string so that the remaining words plus the placeholder fit within the specified width .

# Truncate a string using str.format()

You can also use the str.format() method to truncate a string.

Copied!
a_string = 'bobby hadz com one two three' new_str = ''.format(a_string) print(new_str) # 👉️ bobby new_str = ''.format(a_string) print(new_str) # 👉️ bobby h new_str = ''.format(a_string) print(new_str) # 👉️ bob

The digit after the period is used to specify how many characters are going to be used from the string.

The str.format method performs string formatting operations.

Copied!
first = 'bobby' last = 'hadz' result = "Name: <> <>".format(first, last) print(result) # 👉️ "Name: bobby hadz"

The string the method is called on can contain replacement fields specified using curly braces <> .

You can use the ternary operator if you need to add an ellipsis if the string has a length of more than N.

Copied!
a_string = 'bobby hadz com one two three' new_str = ''.format(a_string) + ". " if len(a_string) > 5 else "" print(new_str) # 👉️ bobby.

The string in the example has more than 5 characters, so the if statement runs and an ellipsis is added at the end.

Want to learn more about truncating strings in Python ? Check out these resources: Get the first N characters of a String in Python ,Remove the last N characters from a String in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Apache with mod php
Оцените статью