Магические методы: __str__, __repr__, __len__, __abs__

Оглавление

“Старая-школа” форматирования строк в Python

До Python 3.6 у нас было два основных способа встраивания выражений Python в строковые литералы для форматирования: % — форматирование и str.format(). Рассмотрим, как их использовать и каковы их ограничения.

Вариант #1: % — форматирование

Этот способ форматирования Python существует в языке с самого его начала. Вы можете прочитать о нем больше информации в . Имейте в виду, что % — форматирование не рекомендуется к использованию:

Как используется % — форматирование

Строковые объекты имеют встроенную операцию с использованием оператора %, который можно использовать для форматирования строк. Вот как это выглядит на практике:

>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'

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

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello Eric. You are 74.'

Недостатки % — форматирования

Примеры кода, которые вы только что видели выше, достаточно читабельны. Однако, как только вы начнете использовать несколько параметров и более длинные строки, ваш код быстро станет менее читаемым. Все начинает выглядеть немного грязно:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

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

Вариант #2: str.format()

Этот новый способ вывода строк был представлен в Python 2.6. Вы можете обратиться к для получения дополнительной информации.

Как используется str.format()

str.format() — это улучшение % — форматирования. Он использует обычный синтаксис вызова функции и метода __format__() для объекта, преобразуемого в строку.

С помощью str.format() поля вывода переменных отмечены фигурными скобками:

>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'

Вы можете ссылаться на переменные в любом порядке, ссылаясь по их индексам:

>>> "Hello, {1}. You are {0}.".format(age, name)
'Hello, Eric. You are 74.'

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

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person, age=person)
'Hello, Eric. You are 74.'

Вы также можете использовать символ **, чтобы использовать этот трек со словарями:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(**person)
'Hello, Eric. You are 74.'

str.format() определенно является улучшением по сравнению с % — форматированием, но и у него есть свои недостатки.

В чем недостатки str.format()

Код, использующий str.format(), гораздо легче читается, чем код, использующий % -форматирование, но str.format() все еще может быть достаточно многословным, когда вы имеете дело с несколькими параметрами и более длинными строками. Посмотрите на это:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> print(("Hello, {first_name} {last_name}. You are {age}. " + 
>>>        "You are a {profession}. You were a member of {affiliation}.") \
>>>        .format(first_name=first_name, last_name=last_name, age=age, \
>>>                profession=profession, affiliation=affiliation))
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

Если у вас есть переменные, которые вы хотите передать в .format() в словаре, то вы можете просто распаковать его с помощью .format (** some_dict) и ссылаться на значения по ключу в строке.

Как определяется длина строки Python?

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

Чтобы продемонстрировать этот метод в действии, найдем длину предложения:

open_source = "Sammy contributes to open source."
print(len(open_source))

Вывод:

33

Мы инициализируем переменную open_source строковым значением «Sammy contributes to open source.». Затем передаем эту переменную в метод len() с помощью len(open_source). После этого используем  print() для вывода результата на экран.

Помните, что любой символ, заключенный в одинарные или двойные кавычки, будет учитываться методом len().

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

Строка — это последовательность символов. Встроенный строковый класс в Python представлен строками, использующими универсальный набор символов Unicode. Строки реализуют часто встречающуюся последовательность операций в Python наряду с некоторыми дополнительными методами, которые больше нигде не встречаются. На картинке ниже показаны все эти методы:

Встроенные строковые функции в Python

Давайте узнаем, какие используются чаще всего

Важно заметить, что все строковые методы всегда возвращают новые значения, не меняя исходную строку и не производя с ней никаких действий

Код для этой статьи можно взять из соответствующего репозитория Github Repository.

1. center( )

Метод выравнивает строку по центру. Выравнивание выполняется с помощью заданного символа (пробела по умолчанию).

Синтаксис

, где:

  • length — это длина строки
  • fillchar—это символ, задающий выравнивание

Пример

2. count( )

Метод возвращает счёт или число появлений в строке конкретного значения.

Синтаксис

, где:

  • value — это подстрока, которая должна быть найдена в строке
  • start — это начальное значение индекса в строке, где начинается поиск заданного значения
  • end — это конечное значение индекса в строке, где завершается поиск заданного значения

Пример

3. find( )

Метод возвращает наименьшее значение индекса конкретной подстроки в строке. Если подстрока не найдена, возвращается -1.

Синтаксис

, где:

  • value или подстрока, которая должна быть найдена в строке
  • start — это начальное значение индекса в строке, где начинается поиск заданного значения
  • end — это конечное значение индекса в строке, где завершается поиск заданного значения

Пример

Метод возвращает копию строки, преобразуя все заглавные буквы в строчные, и наоборот. 

Синтаксис

Пример

5. startswith( ) and endswith( )

Метод возвращает True, если строка начинается с заданного значения. В противном случае возвращает False.

С другой стороны, функция возвращает True, если строка заканчивается заданным значением. В противном случае возвращает False.

Синтаксис

  • value — это искомая строка в строке
  • start — это начальное значение индекса в строке, где начинается поиск заданного значения
  • end — это конечное значение индекса в строке, где завершается поиск заданного значения

Пример

6. split( )

Метод возвращает список слов в строке, где разделителем по умолчанию является пробел.

Синтаксис

  • sep: разделитель, используемый для разделения строки. Если не указано иное, разделителем по умолчанию является пробел
  • maxsplit: обозначает количество разделений. Значение по умолчанию -1, что значит «все случаи»

Пример

7. Строка заглавными буквами

Синтаксис

Синтаксис

Синтаксис

Пример

8. ljust( ) и rjust( )

С помощью заданного символа (по умолчанию пробел) метод возвращает вариант выбранной строки с левым выравниванием. Метод rjust() выравнивает строку вправо.

Синтаксис

  • length: длина строки, которая должна быть возвращена
  • character: символ для заполнения незанятого пространства, по умолчанию являющийся пробелом

Пример

9. strip( )

Метод возвращает копию строки без первых и последних символов. Эти отсутствующие символы — по умолчанию пробелы.

Синтаксис

character: набор символов для удаления

  • : удаляет символы с начала строки.
  • : удаляет символы с конца строки.

10. zfill( )

Метод zfill() добавляет нули в начале строки. Длина возвращаемой строки зависит от заданной ширины.

Синтаксис

width: указывает длину возвращаемой строки. Нули не добавляются, если параметр ширины меньше длины первоначальной строки.

Пример

Заключение

В статье мы рассмотрели лишь некоторые встроенные строковые методы в Python. Есть и другие, не менее важные методы, с которыми при желании можно ознакомиться в соответствующей документации Python.

  • PEG парсеры и Python
  • Популярные лайфхаки для Python
  • Овладей Python, создавая реальные приложения. Часть 1

Перевод статьи Parul PandeyUseful String Method

Multiline Strings

>>> «»»Это пример
…многострочной
…переменной типа
..str»»»

‘Это пример\nмногострочной\nпеременной типа\nstr’

Каждый перенос строки представлен символом \n. Я
выделил его жёлтым для наглядности. Для Python это такой же символ как и остальные просто созданный с помощью

, о котором мы поговорим чуть ниже.

Зададим переменной s значение с использованием \n

>>> s = ‘Это пример\nмногострочной\nпеременной типа\nstr’
>>> print(s)

Это пример
многострочной
переменной типа
str

Точно такой же результат можно получить используя «»» «»»

>>> s = «»»Это пример
… многострочной
… переменной типа
… str»»»
>>> print(s)

Это пример
многострочной
переменной типа
str

Python replacing strings

The method replaces substrings in a string
with other substrings. Since strings in Python are immutable, a new
string is built with values replaced.

replace(old, new )

By default, the method replaces all occurrences of a
substring. The method takes a third argument which limits the replacements
to a certain number.

replacing.py

#!/usr/bin/env python

# replacing.py

a = "I saw a wolf in the forest. A lonely wolf."

b = a.replace("wolf", "fox")
print(b)

c = a.replace("wolf", "fox", 1)
print(c)

We have a sentence where we replace ‘wolf’ with ‘fox’.

b = a.replace("wolf", "fox")

This line replaces all occurrences of the ‘wolf’ with ‘fox’.

c = a.replace("wolf", "fox", 1)

Here we replace only the first occurrence.

$ ./replacing.py
I saw a fox in the forest. A lonely fox.
I saw a fox in the forest. A lonely wolf.

This is the output.

Expression evaluation

The expressions that are extracted from the string are evaluated in
the context where the f-string appeared. This means the expression has
full access to local and global variables. Any valid Python expression
can be used, including function and method calls.

Because the f-strings are evaluated where the string appears in the
source code, there is no additional expressiveness available with
f-strings. There are also no additional security concerns: you could
have also just written the same expression, not inside of an
f-string:

>>> def foo():
...   return 20
...
>>> f'result={foo()}'
'result=20'

Is equivalent to:

>>> 'result=' + str(foo())
'result=20'

Expressions are parsed with the equivalent of ast.parse('(' +
expression + ')', '<fstring>', 'eval')
.

Note that since the expression is enclosed by implicit parentheses
before evaluation, expressions can contain newlines. For example:

Отступы в переменных

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

Для этого добавьте в фигурные скобки после индекса через двоеточие длину поля (в символах). Например:

По умолчанию строки выравниваются внутри поля по левому краю, а числа – по правому краю. Это можно изменить с помощью символов:

  • < – выравнивание по левому краю;
  • ^ – выравнивание по центру;
  • > – выравнивание по правому краю.

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

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

Эти параметры можно комбинировать с другими параметрами, например:

В фигурных скобках указан индекс, длина поля в символах, затем количество символов после точки и тип данных.

Unicode

Python поддерживает Unicode так как по дефолту в нём используется UTF-8

Это позволяет использовать юникод символы без заморочек

>>> «Pythonia voi käyttää myös vaativassa ja tieteellisessä»

‘Pythonia voi käyttää myös vaativassa ja tieteellisessä’

Если бы поддержки не было скорее всего пришлось бы заменять специальные символы, такие как умлауты, на из юникод представление

>>> «Pythonia voi k\u00e4ytt\u00e4\u00e4 my\u00f6s vaativassa ja tieteellisess\u00e4»

‘Pythonia voi käyttää myös vaativassa ja tieteellisessä’

Можно получить юникод символы и другими способами

‘\xe4’

‘ä’

Производительность

F-строки не только гибкие, но и быстрые. И для сравнения производительности разных подходов к форматированию я подготовил два шаблона:

  • простой, в который нужно вставить всего два значения: строку и число;
  • сложный, данные для которого собираются из разных переменных, а внутри происходит преобразование даты, вещественного числа, а также округление.

Финальная простая строка получается такой:

Сложная строка на выходе такая:

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

После недолгого тестирования я получил следующие результаты:

На простых примерах f-строки показывают самые лучшие результаты.На 25% быстрее %-форматирования и метода format().

Triple Quotes

Python’s triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.

The syntax for triple quotes consists of three consecutive single or double quotes.

#!/usr/bin/python3

para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets , or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)

When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the «up.» and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n) −

this is a long string that is made up of
several lines and non-printable characters such as
TAB (    ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets , or just a NEWLINE within
the variable assignment will also show up.

Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −

#!/usr/bin/python3

print ('C:\\nowhere')

When the above code is executed, it produces the following result −

C:\nowhere

Now let’s make use of raw string. We would put expression in r’expression’ as follows −

#!/usr/bin/python3

print (r'C:\\nowhere')

When the above code is executed, it produces the following result −

C:\\nowhere

String Formatting Operator

One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −

#!/usr/bin/python3

print ("My name is %s and weight is %d kg!" % ('Zara', 21)) 

When the above code is executed, it produces the following result −

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with % −

Sr.No. Format Symbol & Conversion
1

%c

character

2

%s

string conversion via str() prior to formatting

3

%i

signed decimal integer

4

%d

signed decimal integer

5

%u

unsigned decimal integer

6

%o

octal integer

7

%x

hexadecimal integer (lowercase letters)

8

%X

hexadecimal integer (UPPERcase letters)

9

%e

exponential notation (with lowercase ‘e’)

10

%E

exponential notation (with UPPERcase ‘E’)

11

%f

floating point real number

12

%g

the shorter of %f and %e

13

%G

the shorter of %f and %E

Other supported symbols and functionality are listed in the following table −

Sr.No. Symbol & Functionality
1

*

argument specifies width or precision

2

left justification

3

&plus;

display the sign

4

<sp>

leave a blank space before a positive number

5

#

add the octal leading zero ( ‘0’ ) or hexadecimal leading ‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were used.

6

pad from left with zeros (instead of spaces)

7

%

‘%%’ leaves you with a single literal ‘%’

8

(var)

mapping variable (dictionary arguments)

9

m.n.

m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

Шаблоны и новая методика форматирования строк

Этот метод был добавлен в Python 2.4 в виде шаблонов строк, но в качестве обычного метода string, работающего через метод format в версии 2.6. Так что это не самый свежий метод, просто обновленный. В любом случае, приступим к работе с шаблонами!

Python

print(«%(lang)s is fun!» % {«lang»:»Python»}) # Python is fun!

1 print(«%(lang)s is fun!»%{«lang»»Python»})# Python is fun!

Должно быть это выглядит странно, но на самом деле мы сменили наши % на %(lang), с тем отличием, что данный объект идет в комплекте с переменной. Вторая часть пример вызывает словарь Python, который мы рассмотрим в следующей статье. В основном, это пара key:value, так что когда Python ищет ключ lang в строке и в указанном словаре ключей, он заменяет этот ключ его значением. Давайте взглянем на следующие примеры:

Python

a = «%(value)s %(value)s %(value)s !» % {«value»:»SPAM»}
print(a) # SPAM SPAM SPAM !

b = «%(x)i + %(y)i = %(z)i» % {«x»:1, «y»:2}
print(b)

Traceback (most recent call last):
File «<string>», line 1, in <fragment>
KeyError: ‘z’

c = «%(x)i + %(y)i = %(z)i» % {«x»:1, «y»:2, «z»:3}
print(c) # 1 + 2 = 3

1
2
3
4
5
6
7
8
9
10
11
12

a=»%(value)s %(value)s %(value)s !»%{«value»»SPAM»}

print(a)# SPAM SPAM SPAM !

b=»%(x)i + %(y)i = %(z)i»%{«x»1,»y»2}

print(b)

Traceback(most recent call last)

File»<string>»,line1,in<fragment>

KeyError’z’

c=»%(x)i + %(y)i = %(z)i»%{«x»1,»y»2,»z»3}

print(c)# 1 + 2 = 3

В первом примере вы могли заметить, что мы передали только одно значение, но оно было вставлено три раза. Это одно из преимуществ использования шаблонов. Второй пример был загвоздкой, в которой мы забыли передать ключ z. В третьем примере эта проблема была исправлена с соответствующим результатом. Теперь давайте взглянем на то, что мы можем сделать, по аналогии с методом форматирования строк:

Python

a = «Python is as simple as {0}, {1}, {2}».format(«a», «b», «c»)
print(a) # ‘Python is as simple as a, b, c’

b = «Python is as simple as {1}, {0}, {2}».format(«a», «b», «c»)
print(b) # ‘Python is as simple as b, a, c’

xy = {«x»:0, «y»:10}
c = «Graph a point at where x={x} and y={y}».format(**xy)
print(c) # Graph a point at where x=0 and y=10

1
2
3
4
5
6
7
8
9

a=»Python is as simple as {0}, {1}, {2}».format(«a»,»b»,»c»)

print(a)# ‘Python is as simple as a, b, c’

b=»Python is as simple as {1}, {0}, {2}».format(«a»,»b»,»c»)

print(b)# ‘Python is as simple as b, a, c’

xy={«x»,»y»10}

c=»Graph a point at where x={x} and y={y}».format(**xy)

print(c)# Graph a point at where x=0 and y=10

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

  • Документация Python 2.Х о

Python string stripping white characters

In string processing, we might often end up with a string that
has white characters at the beginning or at the end of a string.
The term white spaces (characters) refers to invisible characters
like new line, tab, space or other control characters. We have
the , , and
methods to remove these characters.

stripping.py

#!/usr/bin/env python

# strippig.py

s = " Eagle  "

s2 = s.rstrip()
s3 = s.lstrip()
s4 = s.strip()

print('{0} {1}'.format(s, len(s)))
print('{0} {1}'.format(s2, len(s2)))
print('{0} {1}'.format(s3, len(s3)))
print('{0} {1}'.format(s4, len(s4)))

We apply the stripping methods on a string word which has
three white spaces. One space at the start and two spaces
at the end. Note that these methods remove any number of
white spaces, not just one.

s2 = s.rstrip()

The method returns a string with the trailing
white space characters removed.

s3 = s.lstrip()

The method returns a string with the leading
white space characters removed.

s4 = s.strip()

The method returns a copy of the string with
the leading and trailing characters removed.

print('{0} {1}'.format(s2, len(s2)))

The method is used to dynamically build a string.
The is a control character referring
to the first parameter of the method.
The refers to the second parameter.

$ ./stripping.py 
 Eagle   8
 Eagle 6
Eagle   7
Eagle 5

This is the output of the example.

#3 String Interpolation / f-Strings (Python 3.6+)

Python 3.6 added a new string formatting approach called formatted string literals or “f-strings”. This new way of formatting strings lets you use embedded Python expressions inside string constants. Here’s a simple example to give you a feel for the feature:

>>>

As you can see, this prefixes the string constant with the letter ““—hence the name “f-strings.” This new formatting syntax is powerful. Because you can embed arbitrary Python expressions, you can even do inline arithmetic with it. Check out this example:

>>>

Formatted string literals are a Python parser feature that converts f-strings into a series of string constants and expressions. They then get joined up to build the final string.

Imagine you had the following function that contains an f-string:

>>>

When you disassemble the function and inspect what’s going on behind the scenes, you’ll see that the f-string in the function gets transformed into something similar to the following:

>>>

The real implementation is slightly faster than that because it uses the opcode as an optimization. But functionally they’re the same:

>>>

String literals also support the existing format string syntax of the method. That allows you to solve the same formatting problems we’ve discussed in the previous two sections:

>>>

Python’s new formatted string literals are similar to JavaScript’s Template Literals added in ES2015. I think they’re quite a nice addition to Python, and I’ve already started using them in my day to day (Python 3) work. You can learn more about formatted string literals in our in-depth Python f-strings tutorial.

String Methods

Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.

Method Description
capitalize() Converts the first
character to upper case
casefold() Converts string into
lower case
center() Returns a centered
string
count() Returns the number of
times a specified value occurs in a string
encode() Returns an encoded
version of the string
endswith() Returns true if the
string ends with the specified value
expandtabs() Sets the
tab size of the string
find() Searches the string for a
specified value and returns the position of where it was found
format() Formats specified
values in a string
format_map() Formats specified
values in a string
index() Searches the string
for a specified value and returns the position of where it was found
isalnum() Returns True if all
characters in the string are alphanumeric
isalpha() Returns True if all
characters in the string are in the alphabet
isdecimal() Returns True if all
characters in the string are decimals
isdigit() Returns True if all
characters in the string are digits
isidentifier() Returns True if
the string is an identifier
islower() Returns True if all
characters in the string are lower case
isnumeric() Returns True if
all characters in the string are numeric
isprintable() Returns True if
all characters in the string are printable
isspace() Returns True if all
characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a
title
isupper() Returns True if all
characters in the string are upper case
join() Joins the elements of
an iterable to the end of the string
ljust() Returns a left justified
version of the string
lower() Converts a string into
lower case
lstrip() Returns a left trim
version of the string
maketrans() Returns a
translation table to be used in translations
partition() Returns a tuple
where the string is parted into three parts
replace() Returns a string
where a specified value is replaced with a specified value
rfind() Searches the string for
a specified value and returns the last position of where it was found
rindex() Searches the string for
a specified value and returns the last position of where it was found
rjust() Returns a right justified
version of the string
rpartition() Returns a tuple
where the string is parted into three parts
rsplit() Splits the string at
the specified separator, and returns a list
rstrip() Returns a right trim
version of the string
split() Splits the string at
the specified separator, and returns a list
splitlines() Splits the string
at line breaks and returns a list
startswith() Returns true if
the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower
case becomes upper case and vice versa
title() Converts the first
character of each word to upper case
translate() Returns a
translated string
upper() Converts a string
into upper case
zfill() Fills the string with
a specified number of 0 values at the beginning

❮ Previous
Next ❯