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") print(res)
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') print(res)
Do comment if you have any doubts and suggestions on this Python char string topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.