python - 从字符串末尾分割字符串中的 3 个空格分隔的值?

标签 python string

我有这个字符串:

"peter bull team tunnel rat 10 20 30"

我想做的是从末尾提取最后 3 个值:

 30
 20
 10 

如何以最聪明的方式在 python 中向后剥离最后 3 个字段?

最佳答案

一种简单的方法是使用rsplit:

s = "peter bull team tunnel rat 10 20 30"

n = 3
out = s.rsplit(maxsplit=n)[-n:]
# ['10', '20', '30']

如果你想要一个整数列表:

list(map(int, out))
# [10, 20, 30]

在评论之后,如果您想在最后一位数字之前附加文本,一种方法是:

s, *d = s.rsplit(sep=' ',maxsplit=3)
' '.join([*d, s])
# '10 20 30 peter bull team tunnel rat'

关于python - 从字符串末尾分割字符串中的 3 个空格分隔的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934313/

相关文章:

python - 如何使用递归函数仅将全名列表中的名字应用于新列表

python3 -m pip install VS pip3 install

python - 正则表达式简单的多行问题

ios - 基于另一个 String iOS 生成一个唯一的数字字符串

node.js - 从 golang 执行 nodejs 脚本的最佳方式是什么,该脚本返回一个字符串,然后将该字符串传回 golang 变量?

string - 如何在Powershell中替换字符串?

python - PyAPNs 抛出设备不支持的 IOError 操作

python - 使用 'object' 和 `int` 元素将 Pandas 系列转换为 `nan` dtype

python - 字符串比较 : Actual newline is never recognized as "\n"

java - 如何将 List<List<String[]>> 转换为 String[][][]?