Python slice string by character | Example code

Use the split() method to slice string by a character in Python. The split() method splits a string into a list. You have to provide char as a separator to slice it

string.split(separator, maxsplit) 

The second parameter is used to limit the split. Like if you want to only 1 split then pass 1 value.

Python slice string by character and not index example

Simple example code.

Multiple instances of the special character

my_str = "Hello!Python!Developer!Example"



Python slice string by character

Get only the first index to a variable after the slice

For getting only first-word use index after splitting

my_str = "Hello!Python!Developer!Example"
slice_str = my_str.split("!")


Output: Hello

Slice string into 2 parts with special char

my_str = "Hello!Python!Developer!Example"
slice_str = my_str.split("!", 1)

print(slice_str[0], slice_str[1])

Output: Hello Python!Developer!Example

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