alone
alone

Reputation: 179

delete words after a certain character repetition?

I have strings like:

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

or:

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

I want to delete everything after the third name. For example in the first string , I want to have :

John Lasseter , Pete Docter , Andrew Stanton

how can I do that in python?

Upvotes: 2

Views: 59

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 82078

Strictly speaking you would probably be better suited by a function

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'

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160667

No real need to use re for this; just use the split() method on strings and index the list that is returned:

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 ']

Will give you the first three names in the list, as a list.

Using join() with ",".join(s.split(',')[:3]) will additionally join them together in new string containing the comma-seperated names:

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

Upvotes: 5

Related Questions