String Manipulation in Python
Strings in Python are sequences of characters enclosed in single, double, or triple quotes. Strings are immutable, but Python provides many ways to manipulate them.
Creating strings:
Example:
str1 = "Hello"
str2 = 'Python'
str3 = """This is a
multi-line string"""
Accessing characters:
Use indexing to access individual characters. Indexing starts at 0.
Example:
print(str1[0]) # H
print(str1[-1]) # o (last character)
Slicing strings:
Extract a part of a string using slicing: string[start:end]
Example:
print(str1[0:3]) # Hel
print(str1[:3]) # Hel
print(str1[2:]) # llo
print(str1[::2]) # Hlo (every second character)
String concatenation:
Use + to join strings.
Example:
greeting = "Hello " + "World"
print(greeting) # Hello World
String repetition:
Use * to repeat strings.
Example:
print("Hi! " * 3) # Hi! Hi! Hi!
String methods:
lower(): converts to lowercase
upper(): converts to uppercase
title(): capitalizes first letter of each word
strip(): removes leading and trailing whitespace
replace(old, new): replaces substring
split(): splits string into a list
join(): joins a list of strings into a single string
Example:
text = " Python Programming "
print(text.lower()) # python programming
print(text.upper()) # PYTHON PROGRAMMING
print(text.strip()) # Python Programming
print(text.replace("Python", "Java")) # Java Programming
words = text.split()
print(words) # ['Python', 'Programming']
print("-".join(words)) # Python-Programming
Checking content:
startswith() / endswith(): checks start or end
isalpha(): all letters
isdigit(): all digits
isalnum(): letters or digits
Example:
s = "Python3"
print(s.isalpha()) # False
print(s.isalnum()) # True
print(s.startswith("Py")) # True
String formatting:
f-strings:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old")
format() method:
print("My name is {} and I am {} years old".format(name, age))
% formatting:
print("My name is %s and I am %d years old" % (name, age))
Multiline strings:
Use triple quotes for multiple lines.
Example:
msg = """This is
a multiline
string"""
print(msg)
Escape characters:
\n → new line
\t → tab
\\ → backslash
\' → single quote
\" → double quote
Take quizzes related to this topic and see where you stand!
Start Quiz Now