迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/01/26 浏览次数:

使用将 maxsplit 设置为 1str.rsplit() 方法在最后一次出现分隔符时拆分字符串,例如 my_str.rsplit(',', 1)rsplit() 方法从右边开始拆分,当 maxsplit 设置为 1 时只执行一次拆分。

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 个参数:

  • separator 在每次出现分隔符时将字符串拆分为子字符串
  • maxsplit 最多做maxsplit的分裂,最右边的(可选)

除了从右侧拆分外,rsplit() 的行为类似于 split()

maxsplit 参数设置为 1 时,最多进行 1 次拆分。

如果在字符串中找不到分隔符,则返回仅包含 1 个元素的列表。

my_str = 'one two three four'

my_list = my_str.rsplit('-', 1)

print(my_list)  # 👉️ ['one two three four']

如果我们的字符串以特定分隔符结尾,我们可能会得到令人困惑的结果。

my_str = 'one-two-three-four-'

my_list = my_str.rsplit('-', 1)

print(my_list)  # 👉️ ['one-two-three-four', '']

我们可以使用 str.strip() 方法删除前导或尾随分隔符。

my_str = '-one-two-three-four-'

my_list = my_str.strip('-').rsplit('-', 1)

print(my_list)  # 👉️ ['one-two-three', 'four']

在调用 rsplit() 方法之前,我们使用 str.strip() 方法从字符串中删除任何前导或尾随连字符。

如果我们需要将列表中的结果分配给变量,请从列表中解压值。

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

第一个和第二个变量存储列表中的第一个和第二个项目。

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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便