How to Remove Everything Before a Character in a String in Python?

Estimated read time 1 min read

You can remove everything before a character in a string in Python using string slicing. Here’s an example:

s = 'Hello, world!'
new_s = s[s.index(',')+1:]
print(new_s) # Output: ' world!'

In this example, we have a string (s) that contains a comma (,) followed by a space and some text. We want to remove everything before the comma, including the comma. We achieve this by using string slicing with the index() method to find the position of the comma in the string. The index() method returns the index of the first occurrence of a specified substring in the string. We add 1 to the index to start the slice after the comma. The resulting string (new_s) contains everything after the comma, including the space.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply