[英]Python: Reverse Order Of Words
In my program I pull a string from another file and assign it to a variable (see below) 在我的程序中,我从另一个文件中提取一个字符串并将其分配给一个变量(见下文)
ex1 = 'John Doe'
How would I convert the above string to a different format as seen below? 如何将上面的字符串转换为不同的格式,如下所示? (Note the space after the comma)
(注意逗号后面的空格)
ex2 = 'Doe, John'
Sorry if this question seems trivial but I haven't had much experience with lists and most solutions incorporate lists (so I don't fully understand them). 很抱歉,如果这个问题看似微不足道,但我对列表没有多少经验,大多数解决方案都包含列表(所以我不完全理解它们)。
Any help would be greatly appreciated! 任何帮助将不胜感激!
For the case of 2 names, you can use str.join
with reversed
and str.split
: 对于2名的情况下,你可以使用
str.join
与reversed
和str.split
:
ex1 = 'John Doe'
ex2 = ', '.join(reversed(ex1.split())) # 'Doe, John'
You can also use f-strings (Python 3.6+) via an anonymous function: 您还可以通过匿名函数使用f-strings(Python 3.6+):
ex2 = (lambda x: f'{x[1]}, {x[0]}')(ex1.split()) # 'Doe, John'
It's not clear what you'd like to see for multiple names, eg if middle names are provided. 目前尚不清楚您希望多个名称看到什么,例如,如果提供了中间名称。
Given that you will always have names in "First Last" format, here's a really simple solution: 鉴于您将始终使用“First Last”格式的名称,这是一个非常简单的解决方案:
name = ex1.split(' ')
ex2 = name[1] + ', ' + name[0]
>>> ex2
'Doe, John'
Something like 就像是
ex1 = 'John Doe Smith Brown'
print(', '.join(ex1.split(None, 1)[::-1]))
should do the trick. 应该做的伎俩。
The output is "Doe Smith Brown, John". 输出是“Doe Smith Brown,John”。 If you actually wanted "Brown, Smith, Doe, John", remove that
, 1
parameter (which tells .split()
to only allow one split). 如果您真的想要“Brown,Smith,Doe,John”,请删除
, 1
参数(告诉.split()
只允许一次拆分)。
这适用于您的示例:
', '.join(ex1.split()[::-1])
In addition to the many answers posted, I would like to highlight Python multiple assignment schema and the newly-introduced f-strings (3.6+) which in your case could be used as: 除了发布的许多答案之外,我还想强调Python多重赋值模式和新引入的f-strings (3.6+),在您的情况下可以用作:
name, surname = ex1.split(' ')
ex2 = f"{surname}, {name}"
这应该工作
ext = ", ".join( reversed(ex1.split(" ")))
Using regex: 使用正则表达式:
import re
ex2 = re.sub('(\w+)\s(\w+)', r'\2, \1', ex1)
>>> ex2
'Doe, John'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.