拆分字符串并获取 Python 中的最后一个元素
Split a string and get the last element in Python
使用设置为的str.rsplit()
方法拆分字符串并获取最后一个元素。该方法从右侧拆分,当设置为时只会执行一次拆分。maxsplit
1
rsplit()
maxsplit
1
my_str = 'one,two,three,four' last = my_str.rsplit(',', 1)[-1] print(last) # 👉️ 'four'
我们使用了rsplit()
从右边拆分字符串的方法。
str.rsplit
方法使用提供的分隔符作为分隔符字符串返回字符串中的单词列表。
my_str = 'one two three' print(my_str.rsplit(' ')) # 👉️ ['one', 'two', 'three'] print(my_str.rsplit(' ', 1)) # 👉️ ['one two', 'three']
该方法采用以下 2 个参数:
姓名 | 描述 |
---|---|
分隔器 | 在每次出现分隔符时将字符串拆分为子字符串 |
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.
The last step is to access the last element in the list by accessing the list
item at index -1
.
my_str = 'one,two,three,four' last = my_str.rsplit(',', 1)[-1] print(last) # 👉️ 'four'
You can also use the str.split()
method in a similar way.
my_str = 'one-two-three-four' last = my_str.split('-')[-1] print(last) # 👉️ 'four'
If your string ends with the specific separator, you might get a confusing
result.
my_str = 'one-two-three-four-' last = my_str.rsplit('-', 1)[-1] # 👇️ ['one-two-three-four', ''] print(my_str.rsplit('-', 1)) print(last) # 👉️ ""
You can use the str.strip()
method to remove the leading or trailing
separator.
my_str = 'one-two-three-four-' last = my_str.strip('-').rsplit('-', 1)[-1] print(last) # 👉️ "four"
We used the str.strip()
method to remove any leading or trailing hyphens from
the string before calling the rsplit()
method.