Ali Boukeroui 2 min read

How Python Substring A String

 How Python Substring A String

In this article, we will understand Python Substring and how it works. Python provides many ways to substring a string.

What Is A Python Substring?

In python substring is a sequence of characters within another string, In python, often they call it slicing a string.

It follows this format:

string[start: end: step]

Start: The starting index of the substring. The character in this index is embedded in the substring. If the start is ​​not entered, it is assumed to be equal to 0.

End: The terminating index of the substring. The character in this index is not included in the substring. If the End is not included, or if the specified value exceeds the length of the string, it is assumed to be equal to the length of the string by default.

Step: Every Step character after the current letter to be included. The default value is 1. If the step value is subtracted, it is assumed to be equal to 1.

Python Substring Models:

string[start:end]: Get all word letters from index Start to End -1

string[:end]: Get all word letters from the beginning of the string to End -1

string[start:]: Get all word letters from index Start to the end of the string.

string[start:end:step]: Get all word letters from Start to End -1 discounting every step letter.

Python Substring Examples:

  • Get the first 8 characters of a string

string = "Frontendor"
print(string[0:5])

Output:

> Frontend

Note: print(string[:8]) returns the same value result as print(string[0:8])

  • Get a substring of length 4 from the 3rd character of the string

string = "Frontendor"
print(string[2:6])

Output:

> onte

Note: The start or end index could be a negative number. A negative index means that you start counting from the end of the string instead of the start (i.e from the right to left). Index -1 represents the last letter of the string, -2 represents the second to last letter, and so on…

  • Get the last character of the string

string = "Frontendor"
print(string[-1])

Output:

> r
  • Get the last 6 characters of a string

string = "Frontendor"
print(string[-5:])

Output:

> tendor
  • Get a substring that contains all characters except the last 3 characters and the 1st character

string = "Frontendor"
print(string[1:-4])

Output:

> rontend

With this, we come to an end with this python substring article. I hope you found it useful and you got an idea of slicing and how it helps to create different types of python substring.

MORE USEFUL ARTICLES:


Create Beautiful Websites By Copy-Paste.

Save 200+ hours-worth of designing and coding. 100+ UI Blocks & 6+ Templates With Online Copy-Paste Tool.

screenshot of 100+ UI blocks for websites

© 2020-2021 Frontendor. All Rights Reserved.