Skip to content

Python cut string | Example code

  • by

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 an index value to get the 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 or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *