Skip to main content
 首页 » 编程设计

python之保留 Python 字符串的第一个字

2025年05月04日20freeliver54

假设我有一个全名列表,例如:

names : ["Katie von Martin", "Bob Austin Marley", "John Travolta", "Josh Hartnett"] 

拆分每个字符串并仅保留第一个单词的函数会是什么样子?

def keepFirstName(): 
    for name in names: 
        ???? 

请您参考如下方法:

最简单的是:

def first_names(names): 
    for name in names: 
        yield name.split()[0] 

例如

>>> print list(first_names(["Katie von Martin", "Bob Austin Marley", "John Travolta", "Josh Hartnett"])) 
['Katie', 'Bob', 'John', 'Josh'] 

在某些情况下,如果您只想要第一个单词,您可能不想拆分字符串……例如如果字符串真的 很长。在这种情况下,您可以使用 str.find 获取字符串中第一个空格的位置,然后您可以切片到该点以仅提供名字:

>>> def first_names(names): 
...     for name in names: 
...         idx = name.find(' ') 
...         yield name[:idx] if idx > 0 else name 
...  
>>> print list(first_names(["Katie von Martin", "Bob Austin Marley", "John Travolta", "Josh Hartnett"])) 
['Katie', 'Bob', 'John', 'Josh'] 

然而,在实践中,这几乎从来没有必要。