By Ankit Sir • DevTeam
In this chapter, we will learn about strings in Python. We will understand what a string is, how to write strings, indexing, slicing, string functions, and escape sequence characters.
A string is a data type in Python. It is a sequence of characters. Strings are always written inside quotes.
We can write a string in three different ways:
a = 'Ankit' # Single-quoted string
b = "Ankit" # Double-quoted string
c = '''Ankit''' # Triple-quoted string
Note: Triple-quoted strings are useful for writing multi-line strings.
In Python, string indexing starts from 0. Index range is from 0 to (length − 1).
name = "Ankit"
A n k i t
0 1 2 3 4
Length of "Ankit" = 5
String slicing is used to extract a part of a string.
Syntax: string[start : end]
name = "Ankit"
s1 = name[0:3] # 'Ank'
s2 = name[1:3] # 'nk'
Python allows negative indexing. Negative indices start from the end of the string.
name = "Ankit"
name[-1] # 't'
name[-2] # 'i'
Python provides default values for slicing if start or end index is not given.
word = "amazing"
word[:7] # same as word[0:7] → 'amazing'
word[0:] # same as word[0:7] → 'amazing'
Syntax: string[start : end : skip]
word = "amazing"
word[1:6:2]
Output: mzn
Characters are skipped by 2 steps.
len("Ankit") # 5
"Ankit".endswith("kit") # True
"Hurry".count("r") # 2
"python".capitalize() # Python
text = "I love Python programming"
text.find("Python") # 7
text = "I love Java"
text.replace("Java", "Python")
Escape sequences start with a backslash (\) and are used to represent special characters inside strings.
print("Hello\nWorld")
print("Hello\tWorld")
print('It\'s Python')
print("This is a backslash: \\")