0

Need Generalize Solution I have a string and want to remove all characters before the colon (:). Like this:

oldstring = 'Resolution: 1366 x 768'
newstring = '1366 x 768'
kederrac
  • 15,932
  • 5
  • 29
  • 52
Sharyar Vohra
  • 174
  • 1
  • 11

3 Answers3

2

you can use:

newstring = oldstring.split(':')[-1].strip()

for your example:

newstring, _ = oldstring.split(':')
newstring = newstring.strip()
kederrac
  • 15,932
  • 5
  • 29
  • 52
2

You may use

newstring = oldstring[oldstring.find(":") + 1:]

It will remove everything before the first :.

To remove everything before the last :, use this instead :

newstring = oldstring[oldstring.rfind(":") + 1:]

If you want to remove spaces that can trail the :, add strip()

newstring = oldstring[oldstring.find(":") + 1:].strip()

This code will not throw an Exception if there is no : in the string, it will simply not remove anything. If you want to have an Exception in order to handle it, you should use

newstring = oldstring[oldstring.index(":") + 1:]

or

newstring = oldstring[oldstring.rindex(":") + 1:]
Valentin M.
  • 534
  • 5
  • 19
1

It's also an option:

newstring = oldstring[oldstring.find(':') + 1:]
Giannis Clipper
  • 682
  • 4
  • 9