Python string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.
Python slice string
Python slice string syntax is:
1 2 3 |
str_object[start_pos:end_pos:step] |
The slicing starts with the start_pos index (included) and ends at end_pos index (excluded). The step parameter is used to specify the steps to take from start to end index.
Python String slicing always follows this rule: s[:i] + s[i:] == s for any index ‘i’.
All these parameters are optional – start_pos default value is 0, the end_pos default value is the length of string and step default value is 1.
Let’s look at some simple examples of string slice function to create substring.
1 2 3 4 5 |
s="HelloWorld" print(s[:]) print(s[::]) |
Output:
1 2 3 4 |
HelloWorld HelloWorld |
Note that since none of the slicing parameters were provided, the substring is equal to the original string.
Let’s look at some more examples of slicing a string.
1 2 3 4 5 6 7 |
s="HelloWorld" first_five_chars = s[:5] print(first_five_chars) third_to_fifth_chars = s[2:5] print(third_to_fifth_chars) |
Output:
1 2 3 4 |
Hello llo |
Note that index value starts from 0, so start_pos 2 refers to the third character in the string.
Reverse a String using Slicing
We can reverse a string using slicing by providing the step value as -1.
1 2 3 4 5 |
s="HelloWorld" reverse_str = s[::-1] print(reverse_str) |
Output: dlroWolleH
Let’s look at some other examples of using steps and negative index values.
1 2 3 4 |
s1 = s[2:8:2] print(s1) |
Output: loo
Here the substring contains characters from indexes 2,4 and 6.
1 2 3 4 |
s1 = s[8:1:-1] print(s1) |
Output: lroWoll
Here the index values are taken from end to start. The substring is made from indexes 1 to 7 from end to start.
1 2 3 4 |
s1 = s[8:1:-2] print(s1) |
Output: lool
Python slice works with negative indexes too, in that case, the start_pos is excluded and end_pos is included in the substring.
1 2 3 4 |
s1 = s[-4:-2] print(s1) |
Output: or
Python string slicing handles out of range indexes gracefully.
1 2 3 4 5 6 7 |
>>>s="Python" >>>s[100:] '' >>>s[2:50] 'thon' |
That’s all for python string slice function to create substring.