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

时间:2016-01-23 19:42:56

标签: python regex string

我有像:

这样的字符串
'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中做到这一点?

2 个答案:

答案 0 :(得分:5)

确实不需要使用public class Example { // Private variables defined outside of a method/constructor can // be used anywhere within the class but not outside of the class private String[] array; public Example() { array = new String[6]; } public int length() { return array.length; } } ;只需对字符串使用 split() 方法并索引返回的列表:

re

将列出列表中的前三个名称。

join()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])

答案 1 :(得分:0)

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

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'