A Beginner’s Guide to Python Get Substring From a String – Python Tutorial

By | October 14, 2019

We often have to get a substring from a python string in python application, however, there is not a python function to get like php function substring(). In this tutorial, we will introduce to you how to get a substring from a python string.

python get substring from a string

How to get substring from a python string?

We can use:

str[start:end]

to do.

Explain

str: a python string

start: the start position of str you want to get substring

end: the start position of str you want to get substring, str[end] is not in substring.

The length of substring is: end – start.

Here are some examples.

Get a 3 length substring from position 0 in a python string

The length of substring is 3. the start is 0, then end = 3.

text = 'https://www.tutorialexample.com'
#get the substring from 0-3
sub = text[0:3]
print(sub)

The substring is:

htt

Get a 5 length substring from postion 3 in a python string

The length of substring is 5, start is 3 and the end is 8.

text = 'https://www.tutorialexample.com'
#get the substring from 3-8
sub = text[3:8]
print(sub)

The substring is:

ps://

Notice:

1.When start > len(str), the substring will be an empty string

text = 'https://www.tutorialexample.com'
#get the substring from 0-3
sub = text[100:108]
print(type(sub))

The sub is empty, the type of sub is <class ‘str’>.

Leave a Reply

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