Trong mã dưới đây, có một câu trả lời đơn giản, rất hiệu quả và được kiểm tra tốt cho câu hỏi này. Mã này có ý kiến giải thích mọi thứ trong đó.
Tôi hứa nó không đáng sợ như vẻ ngoài của nó - thực sự chỉ có 13 dòng mã! Phần còn lại là tất cả các bình luận, tài liệu và xác nhận
def split_including_delimiters[input: str, delimiter: str]:
"""
Splits an input string, while including the delimiters in the output
Unlike str.split, we can use an empty string as a delimiter
Unlike str.split, the output will not have any extra empty strings
Conequently, len[''.split[delimiter]]== 0 for all delimiters,
whereas len[input.split[delimiter]]>0 for all inputs and delimiters
INPUTS:
input: Can be any string
delimiter: Can be any string
EXAMPLES:
>>> split_and_keep_delimiter['Hello World ! ',' ']
ans = ['Hello ', 'World ', ' ', '! ', ' ']
>>> split_and_keep_delimiter["Hello**World**!***", "**"]
ans = ['Hello', '**', 'World', '**', '!', '**', '*']
EXAMPLES:
assert split_and_keep_delimiter['-xx-xx-','xx'] == ['-', 'xx', '-', 'xx', '-'] # length 5
assert split_and_keep_delimiter['xx-xx-' ,'xx'] == ['xx', '-', 'xx', '-'] # length 4
assert split_and_keep_delimiter['-xx-xx' ,'xx'] == ['-', 'xx', '-', 'xx'] # length 4
assert split_and_keep_delimiter['xx-xx' ,'xx'] == ['xx', '-', 'xx'] # length 3
assert split_and_keep_delimiter['xxxx' ,'xx'] == ['xx', 'xx'] # length 2
assert split_and_keep_delimiter['xxx' ,'xx'] == ['xx', 'x'] # length 2
assert split_and_keep_delimiter['x' ,'xx'] == ['x'] # length 1
assert split_and_keep_delimiter['' ,'xx'] == [] # length 0
assert split_and_keep_delimiter['aaa' ,'xx'] == ['aaa'] # length 1
assert split_and_keep_delimiter['aa' ,'xx'] == ['aa'] # length 1
assert split_and_keep_delimiter['a' ,'xx'] == ['a'] # length 1
assert split_and_keep_delimiter['' ,'' ] == [] # length 0
assert split_and_keep_delimiter['a' ,'' ] == ['a'] # length 1
assert split_and_keep_delimiter['aa' ,'' ] == ['a', '', 'a'] # length 3
assert split_and_keep_delimiter['aaa' ,'' ] == ['a', '', 'a', '', 'a'] # length 5
"""
# Input assertions
assert isinstance[input,str], "input must be a string"
assert isinstance[delimiter,str], "delimiter must be a string"
if delimiter:
# These tokens do not include the delimiter, but are computed quickly
tokens = input.split[delimiter]
else:
# Edge case: if the delimiter is the empty string, split between the characters
tokens = list[input]
# The following assertions are always true for any string input and delimiter
# For speed's sake, we disable this assertion
# assert delimiter.join[tokens] == input
output = tokens[:1]
for token in tokens[1:]:
output.append[delimiter]
if token:
output.append[token]
# Don't let the first element be an empty string
if output[:1]==['']:
del output[0]
# The only case where we should have an empty string in the output is if it is our delimiter
# For speed's sake, we disable this assertion
# assert delimiter=='' or '' not in output
# The resulting strings should be combinable back into the original string
# For speed's sake, we disable this assertion
# assert ''.join[output] == input
return output
Trong hướng dẫn này, chúng tôi sẽ tìm hiểu về phương thức phân chia chuỗi python [] với sự trợ giúp của các ví dụ.
Phương thức split[]
phá vỡ một chuỗi ở dấu phân cách được chỉ định và trả về một danh sách các chuỗi.
Thí dụ
text = 'Python is a fun programming language'
# split the text from space
print[text.split[' ']]
# Output: ['Python', 'is', 'a', 'fun', 'programming', 'language']
Cú pháp của Chuỗi chia []
Cú pháp của split[]
là:
str.split[separator, maxsplit]
Chia [] tham số
Phương thức split[]
mất tối đa 2 tham số:
- phân tách [tùy chọn]- DELIMITER tại đó xảy ra sự chia tách. Nếu không được cung cấp, chuỗi được chia tại khoảng trắng. [optional]- Delimiter at which splits occur. If not provided, the string is splitted at whitespaces.
- MaxSplit [Tùy chọn] - Số lượng phân tách tối đa. Nếu không được cung cấp, không có giới hạn về số lượng chia tách. [optional] - Maximum number of splits. If not provided, there is no limit on the number of splits.
chia [] giá trị trả về
Phương thức split[]
trả về một danh sách các chuỗi.
Ví dụ 1: Làm thế nào chia [] hoạt động trong Python?
text= 'Love thy neighbor'
# splits at space
print[text.split[]]
grocery = 'Milk, Chicken, Bread'
# splits at ','
print[grocery.split[', ']]
# Splits at ':'
print[grocery.split[':']]
Đầu ra
['Love', 'thy', 'neighbor'] ['Milk', 'Chicken', 'Bread'] ['Milk, Chicken, Bread']
Ví dụ 2: Làm thế nào chia [] hoạt động khi MaxSplit được chỉ định?
grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print[grocery.split[', ', 2]]
# maxsplit: 1
print[grocery.split[', ', 1]]
# maxsplit: 5
print[grocery.split[', ', 5]]
# maxsplit: 0
print[grocery.split[', ', 0]]
Đầu ra
['Milk', 'Chicken', 'Bread, Butter'] ['Milk', 'Chicken, Bread, Butter'] ['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk, Chicken, Bread, Butter']
Ví dụ 2: Làm thế nào chia [] hoạt động khi MaxSplit được chỉ định?