Python Strings
A string in Python is a sequence of characters enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ("""...""" or '''...''' for multi-line text). Strings are immutable, meaning calling a string method returns a new string rather than modifying the original in place.
Indexing and Slicing Strings
Characters in a string are zero-indexed, and negative indices count from the end. Slicing with [start:stop] extracts a substring from start up to (but not including) stop:
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:4]) # Pyth
print(word[2:]) # thon
Useful Built-in String Methods
- upper() & lower(): Convert text to uppercase or lowercase.
- strip(): Remove leading and trailing whitespace (or specified characters).
- replace(old, new): Replace occurrences of a substring with another string.
- split(sep): Split a string into a list of substrings based on a delimiter.
raw_text = " Hello, Python World! "
clean_text = raw_text.strip()
print(clean_text.upper())
print(clean_text.replace("Python", "Expertsjava"))
print(clean_text.split(", "))
String Formatting with f-Strings
Use f-strings (formatted string literals prefixed with f or F) to embed variables and expressions directly inside curly braces:
course = "Python"
lessons = 35
summary = f"Course: {course} | Total Lessons: {lessons}"
print(summary)
Tip: Use double quotes around strings that contain apostrophes (such as
"It's a string") so you do not have to escape single quotes manually.