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
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" print(my_str.split("!"))
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("!") print(slice_str)
Slice string into 2 parts with special char
my_str = "Hello!Python!Developer!Example" slice_str = my_str.split("!", 1) print(slice_str, slice_str)
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)
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.