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

Estimated read time 1 min read

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

s = 'hello world!'
new_s = s[:s.index(' ')]
print(new_s) # Output: 'hello'

In this example, we have a string (s) that contains a space character. We want to remove everything after the space character, including the space character itself. We achieve this by using string slicing with the index() method to find the position of the space character. The expression s[:s.index(' ')] returns a new string that contains all characters from the beginning of s up to (but not including) the space character. The resulting string contains everything before the space character.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply