Print specific parts of a string in Python

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Print specific parts of a string in Python #

Use string slicing to print specific parts of a string, e.g. print(my_str[2:5]). The print() function will print the slice of the string starting at the specified index and going up to, but not including the stop index.

main.py
my_str = 'bobbyhadz.com' # ✅ print first 5 characters in string print(my_str[:5]) # 👉️ 'bobby' # ✅ print last 5 characters in string print(my_str[-5:]) # 👉️ 'z.com' # ✅ print slice in the middle of the string start_index = my_str.index('h') stop_index = my_str.index('.') print(my_str[start_index:stop_index]) # 👉️ hadz # ✅ print every 2 characters of the string for i in range(0, len(my_str), 2): print(my_str[i:i+2]) # 👉️ bo, bb, yh, ad, z., co, m

We used string slicing to print specific parts of a string.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The print function takes one or more objects and prints them to sys.stdout.

Note that the print() function returns None, so don't try to store the result of calling print in a variable.

Instead, store the expression in a variable and print the result.

main.py
my_str = 'bobbyhadz.com' first5 = my_str[:5] print(first5) # 👉️ bobby last5 = my_str[-5:] print(last5) # 👉️ z.com

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

If you need to get a slice somewhere in the middle of the string, specify the start and stop indexes.

main.py
my_str = 'bobbyhadz.com' start_index = my_str.index('h') stop_index = my_str.index('.') print(my_str[start_index:stop_index]) # 👉️ hadz print(my_str[5:9]) # 👉️ hadz

The str.index method returns the index of the first occurrence of the provided substring in the string.

The method raises a ValueError if the substring is not found in the string.

Note that the stop index is exclusive (up to, but not including).

If you need to print a slice of every N characters in the string, use the range() class.

main.py
my_str = 'bobbyhadz.com' for i in range(0, len(my_str), 2): print(my_str[i:i+2]) # 👉️ bo, bb, yh, ad, z., co, m

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)
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.