在某个字符重复后删除单词?

2024-06-24 13:41:41 发布

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

我有这样的字符串:

'John Lasseter , Pete Docter , Andrew Stanton , Joe Ranft , Joss Whedon , Andrew Stanton , Joel Cohen , Alec Sokolow '

或:

'Jonathan Hensleigh , Greg Taylor , Jim Strain , Greg Taylor , Jim Strain , Chris Van Allsburg , Chris Van Allsburg'

我想删除第三个名字后面的所有内容。例如,在第一个字符串中,我想要:

John Lasseter , Pete Docter , Andrew Stanton

在python中如何做到这一点?你知道吗


Tags: 字符串johnvanchrisjoetaylorandrewjim
2条回答

无需为此使用re;只需对字符串使用^{}方法,并对返回的列表编制索引:

s = 'John Lasseter , Pete Docter , Andrew Stanton , Joe Ranft , Joss Whedon , Andrew Stanton , Joel Cohen , Alec Sokolow ' 
s.split(',')[:3]
# returns: ['John Lasseter ', ' Pete Docter ', ' Andrew Stanton ']

会给你名单上的前三个名字,作为一个名单。你知道吗

^{}",".join(s.split(',')[:3])一起使用还将把它们连接在一个新字符串中,该字符串包含逗号分隔的名称:

>>> ",".join(s.split(',')[:3])
# returns: 'John Lasseter , Pete Docter , Andrew Stanton '

严格地说,你可能更适合一个函数

def trim_after_repeat(source, delimiter, count = 3):
    # This breaks the string into a list of strings based on your delimiter 
    pieces = source.split(delimiter)
    # This sets items_wanted to match the count you want
    items_wanted = pieces[0:count]
    # This puts the items_wanted back together
    return delimiter.join(items_wanted)

string_to_trim = 'John Lasseter , Pete Docter , Andrew Stanton , Joe Ranft ,'
print(trim_after_repeat(string_to_trim), ' , ')

# 'John Lasseter ,  Pete Docter ,  Andrew Stanton'

相关问题 更多 >