Strings and String Methods
Python Programming
Strings and String Methods
Strings are one of the most commonly used data types in Python. A string is an immutable sequence of characters used to represent text. Whether you are processing user input, reading files, communicating with web APIs, or generating output, you will work with strings constantly. Python provides an exceptionally rich set of built-in methods for string manipulation, making it one of the best languages for text processing tasks.
Creating Strings
Python allows you to create strings using single quotes, double quotes, or triple quotes. There is no difference between single and double quotes — use whichever is more convenient. Triple quotes are used for multi-line strings and docstrings.
# Single and double quotes
name = 'Alice'
greeting = "Hello, World!"
# Escaping quotes
message = "She said, \"Hello!\""
path = 'C:\\Users\\Documents'
# Raw strings (ignore escape sequences)
raw_path = r'C:\Users\Documents'
# Triple-quoted strings (multi-line)
poem = '''Roses are red,
Violets are blue,
Python is great,
And so are you.'''
# Empty string
empty = ""
String Indexing and Slicing
Strings in Python are sequences, meaning each character has an index position starting at 0. You can access individual characters using indexing and extract substrings using slicing.
text = "Hello, Python!"
# Indexing (0-based)
print(text[0]) # 'H'
print(text[7]) # 'P'
print(text[-1]) # '!' (last character)
print(text[-6]) # 'y'
# Slicing [start:end:step]
print(text[0:5]) # 'Hello'
print(text[7:13]) # 'Python'
print(text[:5]) # 'Hello' (start defaults to 0)
print(text[7:]) # 'Python!' (end defaults to length)
print(text[::2]) # 'Hlo yhn' (every 2nd character)
print(text[::-1]) # '!nohtyP ,olleH' (reversed)
# Strings are immutable
# text[0] = 'h' # TypeError! Cannot modify in place
Essential String Methods
Python strings come with dozens of built-in methods. Here are the most important ones you will use daily in your programming career.
text = " Hello, World! "
# Case methods
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.title()) # " Hello, World! "
print(text.capitalize()) # " hello, world! "
print(text.swapcase()) # " hELLO, wORLD! "
# Whitespace removal
print(text.strip()) # "Hello, World!"
print(text.lstrip()) # "Hello, World! "
print(text.rstrip()) # " Hello, World!"
# Searching
print(text.find("World")) # 9 (index of first occurrence)
print(text.find("Python")) # -1 (not found)
print(text.count("l")) # 3
print(text.startswith(" H")) # True
print(text.endswith("! ")) # True
# Replacing
print(text.replace("World", "Python")) # " Hello, Python! "
# Splitting and joining
csv_data = "apple,banana,cherry"
fruits = csv_data.split(",") # ['apple', 'banana', 'cherry']
joined = " | ".join(fruits) # "apple | banana | cherry"
sentence = " Hello World "
words = sentence.split() # ['Hello', 'World'] (splits on whitespace)
# Checking content
print("hello123".isalnum()) # True
print("hello".isalpha()) # True
print("12345".isdigit()) # True
print("hello".islower()) # True
print("
".isspace()) # True
String Formatting
Python offers several ways to format strings. The modern f-string approach (introduced in Python 3.6) is the most readable and performant option.
name = "Alice"
age = 30
gpa = 3.856
# f-strings (recommended — Python 3.6+)
print(f"Name: {name}, Age: {age}")
print(f"GPA: {gpa:.2f}") # "GPA: 3.86" (2 decimal places)
print(f"{'Python':>20}") # Right-aligned in 20 chars
print(f"{'Python':^20}") # Center-aligned
print(f"{1000000:,}") # "1,000,000" (thousands separator)
print(f"{0.75:.1%}") # "75.0%" (percentage format)
# Expressions inside f-strings
print(f"2 + 3 = {2 + 3}")
print(f"Upper: {name.upper()}")
items = ['a', 'b', 'c']
print(f"Count: {len(items)}")
# .format() method (older style)
print("Name: {}, Age: {}".format(name, age))
print("Name: {n}, Age: {a}".format(n=name, a=age))
# % formatting (oldest style — avoid in new code)
print("Name: %s, Age: %d" % (name, age))
Pro tip: f-strings can contain any valid Python expression, including function calls, ternary expressions, and even list comprehensions. They are evaluated at runtime, so they always reflect the current value of variables.
Key Takeaways
- Strings are immutable sequences of characters; use single, double, or triple quotes to create them.
- Slicing with
[start:end:step]is a powerful way to extract substrings, and negative indices count from the end. - Essential methods include
strip(),split(),join(),replace(),find(),upper(), andlower(). - Use f-strings (f"...") for string formatting — they are the most readable and efficient option in modern Python.
- Since strings are immutable, methods like
replace()return a new string rather than modifying the original.