join(), split()
https://docs.python.org/3/library/stdtypes.html
join() - метод
str = "D
".join(list/tuple)
Метод join()
приймає всі елементи в ітеруючому об’єкті та об’єднує їх в один рядок, розділяючи роздільником D
. Елементи повинні бути строкового типу str!
my_tuple = ("John", "Peter", "Vicky")
x = "-".join(my_tuple)
print(x) # 'John-Peter-Vicky'
split() - метод
list = str.split("D
", maxsplit)
Розділяє рядок на частини по роздільнику D
, повертає список частин:
txt = "welcome to the jungle"
x = txt.split()
print(x) # ['welcome', 'to', 'the', 'jungle']
y = txt.split('o')
print(y) # ['welc', 'me t', 'the jungle']
z = txt.split(' ', 1)
print(z) # ['welcome', 'to the jungle']
див.також .rsplit()
, .partition()
, .splitlines()
,
rsplit()
list = str.rsplit("D
", rightmaxsplit)
Аналогічно split()
, тільки rightmaxsplit рахується зправа
txt = "Perl Java Python"
x = txt.rsplit()
print(x) # ['Perl', 'Java', 'Python']
z = txt.split(' ', 1)
print(z) # ['Perl Java', 'Python']
partition()
list_length_3 = str.partition("D
")
Розбиває рядок на три частини по роздільнику. Повертає кортеж з трьох елементів: частина рядка до роздільника, роздільник, частина рядка після роздільника. Якщо роздільник не знайдений - дивися приклад:
txt = "7.40"
x = txt.partition(".")
print(type(x)) # <class 'tuple'>
print(x) # ('7', '.', '40')
x = txt.partition(",")
print(x) # ('7.40', '', '')
splitlines()
list = str.splitlines(keepends=False)
Метод splitlines()
розбиває рядок на список. Поділ виконується на розривах рядків. З True
зберігає розриви рядків у елементах списку.
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines()
print(x) # ['Thank you for the music', 'Welcome to the jungle']
x = txt.splitlines(True)
print(x) # ['Thank you for the music\n', 'Welcome to the jungle']
x = txt.splitlines(False)
print(x) # ['Thank you for the music', 'Welcome to the jungle']
Representation
Description
\n
Line Feed
\r
Carriage Return
\r\n
Carriage Return + Line Feed
та інші... (див https://docs.python.org/3/library/stdtypes.html#str.splitlines)
Last updated