python - 在 Python 中,是否可以在一个表达式中将列表拆分为第一个、内部和最后一个元素?

标签 python python-3.x string split

想象一个字符串 s="one two three four five"。我想把它分成第一个、最后一个和“内部”元素。我知道我可以通过巧妙的拆包和重新加入来做到这一点:

first, *rest, last = s.split(" ")
middle = " ".join(rest)
print(first, middle, last)

是否可以在一个表达式中做到这一点? (即可能不先拆分整个字符串然后再重新加入)

最佳答案

使用 re 模块 ( regex101 ):

s="one two  three   four five"

import re
first, middle, last = re.findall(r'(\S+)\s*(.*)\s+(\S+)', s)[0]

print(first)
print(middle)
print(last)

打印:

one
two  three   four
five

关于python - 在 Python 中,是否可以在一个表达式中将列表拆分为第一个、内部和最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57521695/

相关文章:

python - 使用 psycopg2 与 postgresql 的连接被拒绝

python - tkinter.mainloop 函数的 n 参数是什么?

python - 计算 python 中发生的迭代次数

Python-替换字符串中的模式

Python pandas - 根据集体 NaN 计数删除组

python - Unresolved 导入 : webbrowser

python-3.x - Pandas 中的条件列选择

python - 如何在 Python Pandas 中使用逗号作为小数分隔符的浮点格式?

c - 如何限制用户输入字符串的大小或动态分配内存

Java赋值运算符执行