Python cut string | Example code

You can use the split() method to cut strings in Python. The split() method splits a string into a list. The default separator is whitespace but you can use your own like a comma.

string.split(separator, maxsplit) 

After splitting a string use bracket with index value to get cut of the string.

Python cut string example

Simple example code cut the string from every comma.

txt = "hello, my name is John, I am 19 years old"

x = txt.split(", ")

print(x)

Output:

Python cut string

How to fetch all chars of a string before a space in Python?

Answer: Use whitespace as a separator and get the first index value.

s1 = "String king"

res = s1.split(' ')

print(res[0])

Output: String

Do comment if you have any doubts and suggestions on this Python 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.