4. Strings in Python

Strings are used to store text data in Python.

A string is a sequence of characters enclosed in:

  • Single quotes ' '
  • Double quotes " "
  • Triple quotes ''' ''' or """ """

String Creation

Using Single Quotes

name = 'Python'
print(name)

Using Double Quotes

language = "Programming"
print(language)

Using Triple Quotes

Used for multi-line strings.

text = """Python is
easy to learn"""

print(text)

String Indexing

Each character in a string has an index number.

Example:

word = "Python"
CharacterPython
Index012345

Access Characters

word = "Python"

print(word[0])
print(word[2])

Output:

P
t

Negative Indexing

print(word[-1])
print(word[-2])

Output:

n
o

String Slicing

Slicing extracts part of a string.

Syntax

string[start:end]
  • start included
  • end excluded

Examples

text = "Python"

print(text[0:3])
print(text[2:5])

Output:

Pyt
tho

Slicing with Step

print(text[0:6:2])

Output:

Pto

Reverse String

print(text[::-1])

Output:

nohtyP

String Methods

Python provides many built-in string methods.


1. upper()

Converts string to uppercase.

name = "python"

print(name.upper())

Output:

PYTHON

2. lower()

Converts string to lowercase.

print("PYTHON".lower())

3. title()

Capitalizes first letter of each word.

text = "python programming"

print(text.title())

4. strip()

Removes extra spaces.

text = "  Python  "

print(text.strip())

5. replace()

Replaces text.

text = "I like Java"

print(text.replace("Java", "Python"))

6. split()

Splits string into list.

text = "apple,banana,mango"

print(text.split(","))

Output:

['apple', 'banana', 'mango']

7. find()

Returns position of substring.

text = "Python Programming"

print(text.find("Pro"))

8. startswith() and endswith()

text = "Python"

print(text.startswith("Py"))
print(text.endswith("on"))

9. count()

Counts occurrences.

text = "banana"

print(text.count("a"))

Output:

3

Escape Characters

Escape characters are used to include special characters inside strings.


Common Escape Characters

EscapeMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote

Examples

print("Hello\nWorld")

Output:

Hello
World

print("Python\tProgramming")

String Formatting

String formatting inserts values into strings.


1. Using + Operator

name = "Aditya"

print("Hello " + name)

2. Using Comma

age = 25

print("Age:", age)

f-Strings

Introduced in Python 3.6.

Fast and readable method.


Syntax

f"string {variable}"

Example

name = "Aditya"
age = 25

print(f"My name is {name} and I am {age} years old")

Expressions in f-Strings

a = 10
b = 20

print(f"Sum = {a + b}")

.format() Method

Another formatting method.


Example

name = "Aditya"
age = 25

print("My name is {} and age is {}".format(name, age))

Indexed Formatting

print("{0} is learning {1}".format("Aditya", "Python"))

Named Formatting

print("{name} is {age} years old".format(name="Aditya", age=25))

Regular Expressions (re Module)

Regular expressions are used for pattern matching.

Python provides the re module.


Import re

import re

1. findall()

Returns all matches.

import re

text = "Python 123 Java 456"

result = re.findall(r'\d+', text)

print(result)

Output:

['123', '456']

2. search()

Searches first occurrence.

import re

text = "I love Python"

match = re.search("Python", text)

print(match)

3. sub()

Replaces matched text.

import re

text = "I like Java"

new_text = re.sub("Java", "Python", text)

print(new_text)

Output:

I like Python

Common Regex Patterns

PatternMeaning
\dDigit
\DNon-digit
\wWord character
\sSpace
.Any character
^Starts with
$Ends with

Example: Validate Email

import re

email = "test@gmail.com"

pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

if re.match(pattern, email):
print("Valid Email")
else:
print("Invalid Email")