Slice a string at a certain character in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Slice a string at a certain character in Python #

To slice a string at a certain character:

  1. Use the str.split() method to split the string on the character.
  2. Access the list at a given index.
  3. For example, first = my_str.split('_')[0].
main.py
my_str = 'bobby_hadz_com' first = my_str.split('_')[0] print(first) # 👉️ bobby second = my_str.split('_')[1] print(second) # 👉️ hadz # --------------------------------- # 👇️ only split string once first, second = my_str.split('_', 1) print(first) # 👉️ bobby print(second) # 👉️ hadz_com

We used the str.split() method to slice a string at a given character.

The str.split() method splits the string into a list of substrings using a delimiter.

main.py
my_str = 'bobby_hadz_com' print(my_str.split('_')) # 👉️ ['bobby', 'hadz', 'com']

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If the separator is not found in the string, a list containing only 1 element is returned.

We split the string on each underscore in the example, but you can use any other character.

If you only need to split the string once, set the maxsplit argument to 1 in the call to str.split().

main.py
my_str = 'bobby_hadz_com' first, second = my_str.split('_', 1) print(first) # 👉️ bobby print(second) # 👉️ hadz_com

The maxsplit argument can be used to only split the string on the first occurrence of the given character.

main.py
my_str = 'bobby_hadz_com' # 👇️ ['bobby', 'hadz_com'] print(my_str.split('_', 1))

Note that the str.split() method returns a list containing a single item if the character is not in the string.

main.py
my_str = 'bobby_hadz_com' print(my_str.split('@')) # 👉️ ['bobby_hadz_com']

You can use the in operator to check if the character is present in the string.

main.py
my_str = 'bobby_hadz_com' if '_' in my_str: my_list = my_str.split('_') first = my_list[0] print(first) # 👉️ bobby second = my_list[1] print(second) # 👉️ hadz

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.