Python 将全名拆分为两个变量,姓氏可能包含多个单词

新手上路,请多包涵

我有一个全名列表,目前我将其分成两个变量:

 first, last = full_name.split(" ")

仅当拆分时 full_name 是两个词时才有效,否则我得到。有没有一种简洁的方法来解释一个名称,其中有更多部分要保留 first 作为第一个单词, last 作为其余单词?我可以用一两行额外的代码来完成,但我想知道是否有一种优雅的方法。

原文由 Frank Matranga 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 980
2 个回答

由于您使用的是 Python3,因此您还可以使用 Extended Iterable Unpacking

例如:

 name = "John Jacob Jingleheimer Schmidt"
first, *last = name.split()
print("First = {first}".format(first=first))
#First = John
print("Last = {last}".format(last=" ".join(last)))
#Last = Jacob Jingleheimer Schmidt

这会将拆分字符串的第一个元素之后的所有内容存储在 last 中。使用 " ".join(last) 将字符串放回原处。

如果只有两个元素要解包,它也可以工作。

 name = "John Schmidt"
first, *last = name.split()
print("First = {first}".format(first=first))
#First = John
print("Last = {last}".format(last=" ".join(last)))
#Last = Schmidt

或者如果你想要第一个、中间的和最后一个:

 name = "John Jacob Jingleheimer Schmidt"
first, middle, *last = name.split()
print("First = {first}".format(first=first))
#First = John
print("Middle = {middle}".format(middle=middle))
#Middle = Jacob
print("Last = {last}".format(last=" ".join(last)))
#Last = Jingleheimer Schmidt

原文由 pault 发布,翻译遵循 CC BY-SA 3.0 许可协议

查看 split 的第二个参数

first, last = "First Last Second Last".split(" ", 1)

如果 full_name 可以是一个词:

 name_arr = full_name.split(" ", 1)
first = name_arr[0]
last = name_arr[1] if len(name_arr) > 1 else ""

原文由 eqwert 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题