Python cut string before character | Example code

Use the split() method to cut string before the character in Python. The split() method splits a string into a list. After listing into the list take only 0 indexed values.

Python cut string before the character Example

Simple example code cut all chars of a string before a “and” in python. Just use the split function. It returns a list, and keep the first element:

s = "Python and data science"

res = s.split("and")[0]
print(res)

Output:

Python cut string before character

Using str.partition() to get the part of a string before the first occurrence of a specific character

String partition() method return tuple. In the example cut the first occurrence of a “and” character.

s = "Python and data science"

res = s.partition('and')[0]
print(res)

Output: Python

Do comment if you have any doubts and suggestions on this Python char string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.