在 Python 中最后一次出现定界符时拆分字符串

在 Python 中最后一次出现定界符时拆分字符串

Split string on last occurrence of delimiter in Python

使用设置为的str.rsplit()方法在最后一次出现定界符时拆分字符串,例如. 该方法从右边开始拆分,
设置为

时只执行一次拆分
maxsplit1my_str.rsplit(',', 1)rsplit()maxsplit1

主程序
my_str = 'one,two,three,four' my_list = my_str.rsplit(',', 1) print(my_list) # 👉️ ['one,two,three', 'four'] print(my_list[0]) # 👉️ one,two,three print(my_list[1]) # 👉️ four first, second = my_list print(first) # 👉️ 'one,two,three' print(second) # 👉️ 'four'

我们使用该str.rsplit()方法在最后一次出现所提供的分隔符时拆分字符串。

str.rsplit
方法使用提供的分隔符作为分隔符字符串返回字符串中的单词列表

主程序
my_str = 'one two three' print(my_str.rsplit(' ')) # 👉️ ['one', 'two', 'three'] print(my_str.rsplit(' ', 1)) # 👉️ ['one two', 'three']

该方法采用以下 2 个参数:

姓名 描述
分隔器 Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done, the rightmost ones (optional)

Except for splitting from the right, rsplit() behaves like split().

When the maxsplit argument is set to 1, at most 1 split is done.

If the separator is not found in the string, a list containing only 1 element is
returned.

main.py
my_str = 'one two three four' my_list = my_str.rsplit('-', 1) print(my_list) # 👉️ ['one two three four']

If your string ends with the specific separator, you might get a confusing
result.

main.py
my_str = 'one-two-three-four-' my_list = my_str.rsplit('-', 1) print(my_list) # 👉️ ['one-two-three-four', '']

You can use the str.strip() method to remove the leading or trailing
separator.

main.py
my_str = '-one-two-three-four-' my_list = my_str.strip('-').rsplit('-', 1) print(my_list) # 👉️ ['one-two-three', 'four']

We used the str.strip() method to remove any leading or trailing hyphens from
the string before calling the rsplit() method.

If you need to assign the results from the list to variables, unpack the values
from the list.

main.py
my_str = 'one-two-three-four' my_list = my_str.rsplit('-', 1) print(my_list) # 👉️ ['one-two-three', 'four'] first, second = my_list print(first) # 👉️ one-two-three print(second) # 👉️ four

first和变量存储列表中second第一项和第二项。

使用这种方法时,我们必须确保声明的变量与可迭代对象中的项目一样多。