>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Добавление в строку пробелов и ее выравнивание:
>>> a = 'hello'
>>> a.center(10)
' hello '
>>> a.ljust(10)
'hello '
>>> a.rjust(10)
' hello'
>>> a.rjust(3)
'hello'
Количество вхождений подстроки в строку или ее часть:
>>> a = 'hello'
>>> a.center(10)
' hello '
>>> a.ljust(10)
'hello '
>>> a.rjust(10)
' hello'
>>> a.rjust(3)
'hello'
Начинается ли строка или ее часть определенной подстрокой:
>>> b.startswith("ban")
True
>>> b.startswith("-o",6)
True
>>> b.startswith("-o",5)
False
Заканчивается ли строка или ее часть определенной подстрокой:
>>> b.endswith('ge')
True
>>> b.endswith('a-',0,7)
True
>>> b.endswith('a-',0,5)
False
Поиск подстроки в строке (если подстрока не найдена, то генерируетя -1):
>>> s = "H-h-hello world! And hello again."
>>> find("hello", s)
>>> s.find("hello")
4
>>> s.find("hello",10)
21
>>> s.find("hellow")
-1
>>> s.find("o ",15,30)
25
Поиск подстроки в строке (если подстрока не найдена, то генерируетя исключение):
>>> s.index("hellow")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.index("hello")
4
Поиск с конца:
>>> s.rindex("hello")
21
>>> s.rfind("hello")
21
>>> s.rfind("hello",0,20)
4
Замена символов табуляции на табуляцию установленной длины (измеряется в пробелах):
>>> tabs = "e b"
>>> tabs.expandtabs()
'e b'
>>> tabs.expandtabs(16)
'e b'
>>> tabs = "e b"
>>> tabs.expandtabs(16)
'e b'
>>> tabs = "e b"
>>> tabs.expandtabs(16)
'e b'
Удаление пробелов и табуляций в начале и конце строки:
>>> sp = " dkfj"
>>> sp = " dkfj "
>>> sp.lstrip()
'dkfj \t'
>>> sp.rstrip()
' \tdkfj'
>>> sp.strip()
'dkfj'
Замена одной подстоки другой:
>>> a = "This is a ball. It's the red ball. We play ball with."
>>> a.replace("ball","car")
"This is a car. It's the red car. We play car with."
>>> a.replace("ball","car",2)
"This is a car. It's the red car. We play ball with."
Замена символов строки другими символами, удаление, оставление без изменений:
>>> a = str.maketrans('abcde','абвгд','1234567890') # устанавливается соответствие по таблице Unicode >>> a {97: 1072, 98: 1073, 99: 1074, 100: 1075, 101: 1076, 48: None, 49: None, 50: None, 51: None, 52: None, 53: None, 54: None, 55: None, 56: None, 57: None} >>> s = "yes no be y8ou 23" >>> s.translate(a) 'yдs no бд you '
Представление строки в кодировке (по-умолчанию, UTF-8):
>>> 'АБВ'.encode()
b'\xd0\x90\xd0\x91\xd0\x92'
Объединение строк-элементов последовательности:
>>> a = ['ab', 'cde', 'ifg']
>>> '-|-'.join(a)
'ab-|-cde-|-ifg'
Разделение строки:
>>> a = "one two three four"
>>> a.split()
['one', 'two', 'three', 'four']
>>> a.split('o')
['', 'ne tw', ' three f', 'ur']
>>> a.split('o',2)
['', 'ne tw', ' three four']
Разделение строки, содержащей переходы на новую строку:
>>> a = "one\ntwo\nthree\nfour"
>>> print(a)
one
two
three
four
>>> a.splitlines()
['one', 'two', 'three', 'four']
>>> a.splitlines(True)
['one\n', 'two\n', 'three\n', 'four']
Замена первой буквы на прописную:
>>> a = "abc def"
>>> a.capitalize()
'Abc def'
Содержит ли строка только цифры:
>>> a = '123'
>>> b = '1a23'
>>> a.isdigit()
True
>>> b.isdigit()
False
Все ли символы-буквы в нижнем регистре:
>>> a.islower()
False
>>> b.islower()
True
>>> c = 'abCde'
>>> c.islower()
False
Содержит ли строка только символы пробела, табуляции и перехода на новую строку:
>>> a = ' b '
>>> b = ' '
>>> a.isspace()
False
>>> b.isspace()
True
Начинается ли каждое слово в строке с большой буквы:
>>> a = "My name is Tom"
>>> b = "Two Years Ago..."
>>> a.istitle()
False
>>> b.istitle()
True
Все ли символы в верхнем регистре:
>>> a = '123'
>>> b = '1B2'
>>> c = 'ABc'
>>> d = 'ABC'
>>> a.isupper(), b.isupper(), c.isupper(), d.isupper()
(False, True, False, True)
Перевод всех символов в нижний или верхний регистры, смена регистра на противоположный:
>>> a = "One tWo thREE"
>>> a.lower()
'one two three'
>>> a.upper()
'ONE TWO THREE'
>>> a.swapcase()
'oNE TwO THree'
Превращает строку в заголовок на английский манер:
>>> a.swapcase()
'oNE TwO THree'
Все ли символы в строке десятичные цифры (непонятно в чем отличие между isdecimal и isdigit):
>>> '123'.isdecimal()
True
>>> ' 123'.isdecimal()
False
>>> '123 12'.isdecimal()
False
>>> '123 12'.isdigit()
False
Таже проблема с isnumeric().