Chapter 4 - Strings in Python

By Ankit Sir • DevTeam

Chapter 4

Strings in Python

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.

Basics

What is a String?

A string is a data type in Python. It is a sequence of characters. Strings are always written inside quotes.

Syntax

Ways to Write a String

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.

Indexing

String Indexing

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
    
Slicing

String Slicing

String slicing is used to extract a part of a string.

Syntax: string[start : end]

  • Starting index is included
  • Ending index is not included
name = "Ankit"

s1 = name[0:3]   # 'Ank'
s2 = name[1:3]   # 'nk'
    
Indexing

Negative Indexing

Python allows negative indexing. Negative indices start from the end of the string.

  • -1 → Last character
  • -2 → Second last character
name = "Ankit"

name[-1]   # 't'
name[-2]   # 'i'
    
Advanced

Advanced String Slicing

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'
    
Skip

String Slicing with Skip Value

Syntax: string[start : end : skip]

word = "amazing"
word[1:6:2]
    

Output: mzn

Characters are skipped by 2 steps.

Functions

String Functions

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")
    
Special

Escape Sequence Characters

Escape sequences start with a backslash (\) and are used to represent special characters inside strings.

  • \n → New line
  • \t → Tab space
  • \' → Single quote
  • \\ → Backslash
print("Hello\nWorld")
print("Hello\tWorld")
print('It\'s Python')
print("This is a backslash: \\")