0
mylist = ['Arthur Morgan Game Name: Red Dead Redemption2',
'Zealda',
'Geralt Game Name:Witcher3','Uncharted4']

I have a list of strings above and I want to split by "Game Name: " first and only keep the text after the separator. I tried [w.split('Game Name: ') for w in mylist]

What's the next step?

Expected results:

['Red Dead Redemption2','Zealda','Witcher3','Uncharted4']

Thank you!

  • You rely on a single delimiter being present in the string without accounting for 2 or more. Please don't design software for the 737 Max. –  Jul 16 '19 at 15:59

2 Answers2

1
[w.split('Game Name:')[-1] for w in mylist]

Edit According to Martijn Pieters partition() is faster, even when you need to check for empty strings.

[w.partition('Game Name:')[-1] or w for w in mylist]
wilkben
  • 657
  • 3
  • 12
  • You are not accounting for `:` in the game name, and `w.partition(':')[-1]` would be faster. – Martijn Pieters Jul 16 '19 at 15:45
  • Thank you for the help@wilkben –  Jul 16 '19 at 15:48
  • @MartijnPieters While partition is slightly faster, it has different results for strings that don't contain the separator. The added check to see if the separator exists would cancel out any performance benefits. – wilkben Jul 16 '19 at 15:55
  • @wilkben: it *depends on what you want* if that's a problem. And testing if the partition is empty (second element) is still fast. – Martijn Pieters Jul 16 '19 at 16:17
  • 1
    I’ve created a time trial: https://stackoverflow.com/a/57064170. Spoiler alert: `str.partition()` wins, on all fronts. – Martijn Pieters Jul 16 '19 at 20:32
-1
mylist = ['Arthur Morgan Game Name: Red Dead Redemption2',
'Zealda',
'Geralt Game Name:Witcher3','Uncharted4']

gameNames = [w.split(":")[-1].strip(" ") for w in mylist]
print(gameNames)

Returns:

['Red Dead Redemption2', 'Zealda', 'Witcher3', 'Uncharted4']
Jmonsky
  • 1,519
  • 1
  • 9
  • 16
  • You are not accounting for `:` in the game name, and `w.partition(':')[-1]` would be faster. And you could just use `.strip()` without arguments. – Martijn Pieters Jul 16 '19 at 15:46