保留Python字符串的第一个单词吗?

2024-09-30 08:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

分割每个字符串并只保留第一个单词的函数是什么?在

^{pr2}$

Tags: 函数字符串列表namesjohn单词bobmartin
3条回答

最简单的方法是:

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

例如

^{pr2}$

在某些情况下,如果您只想要第一个单词,您可能不想拆分字符串。。。e、 g.如果字符串真的很长。在这种情况下,您可以使用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']

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

要保留它并将其存储在列表中

b=[]
for i in names:
    b.append(i.split()[0])

名单b包含名字

或者,这会给你第一个词:

>>> names = ["Katie von Martin", "Bob Austin Marley", "John Travolta", "Josh Hartnett"]
>>> first_words = [words.split()[0] for words in names]
>>> print first_words 

['Katie', 'Bob', 'John', 'Josh']

相关问题 更多 >

    热门问题