使用将 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

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

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

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐