Python - Substring

By xngo on June 14, 2019

In Python, extracting a substring from a string is called slicing. It follows the following template:

string[start: end: step]
  • start: The starting index of the substring. The character at this index is included in the substring. If start is not included, then it is default to 0.
  • end: The ending index of the substring. The character at this index is NOT included in the substring. If end is not included, or if the specified number exceeds the string length, then it is default to the length of the string.
  • step: Number of character after the current character to be included. If the step number is not included, then it is default to 1.

A negative index for start or end means that you start counting from the end of the string instead of the beginning (i.e from the right to left).

Here are some example showing how to extract substrings.

str = "OpenWritings.net"
 
# Get the first character of the string.
print( str[0] )     # Output: O
 
# Get the last character of the string.
print( str[-1] )    # Output: t
 
# Get substring from the 1st character to the 4th characters.
print( str[0:4] )   # Output: Open
 
# Get substring from the 5th characters until the end.
print( str[4:] )    # Output: Writings.net
 
# Get the last 3 characters.
print( str[-3:] )   # Output: net
 
# Get substring containing all characters except the last 4 characters.
print( str[:-4] )   # Output: OpenWritings
 
# Skip every 1 character.
print( str[::2] )   # Output: OeWiig.e
 
# Copy the full string.
print( str[:] )     # Output: OpenWritings.net

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.