Python Strings ๐งต
What is a String?
Strings in Python are arrays of bytes representing Unicode characters. They are surrounded by either single quotation marks or double quotation marks.
๐ฟ Analogy: The Necklace
Think of a string as a necklace of beads.
Each bead is a character. You can count them (length), look at a specific bead (indexing), or take a section of beads (slicing).
However, you cannot change a single bead on the string once it's made (Immutability). You have to make a whole new necklace!
โจ Creating Strings
# Single or Double quotes are the same
a = "Hello"
b = 'Hello'
# Multiline Strings (Triple Quotes)
c = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit."""๐ Strings are Immutable
This is a very important concept. Once a string is created, it cannot be changed. You cannot modify a character at a specific index.
โ This will cause an error:
a = "Hello"
a[0] = "J" # TypeError: 'str' object does not support item assignmentโ The Solution: Create a New String
a = "Hello"
a = "J" + a[1:] # Create a new string "Jello" and assign it back to 'a'
print(a) # Output: Jello๐ช Slicing Strings
You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon.
b = "Hello, World!"
# Get characters from position 2 to 5 (not included)
print(b[2:5]) # "llo"
# Slice from the start
print(b[:5]) # "Hello"
# Slice to the end
print(b[2:]) # "llo, World!"
# Negative Indexing (Slice from the end)
print(b[-5 : -2]) # "orl"๐ f-Strings (String Formatting)
The modern way to format strings in Python (since version 3.6) is using f-strings. Just put an f before the string and use curly braces for variables.
โจ Best Practice
name = "John"
age = 36
txt = f"My name is {name}, and I am {age} years old."
print(txt)๐ ๏ธ Useful String Methods
Modify
a = " Hello "
print(a.strip()) # "Hello" (Removes whitespace)
print(a.lower()) # " hello "
print(a.upper()) # " HELLO "
print(a.replace("H", "J")) # " Jello "Search & Split
a = "Hello, World!"
print(a.split(",")) # ['Hello', ' World!']
print(a.find("World")) # 7 (Index of first match)๐ฏ Real-World Application: Data Cleaning
String methods are used constantly in Data Science to clean messy user data.
user_input = " joHN@example.COM "
clean_email = user_input.strip().lower()
print(clean_email) # "john@example.com"๐ก Did You Know? Raw Strings
If you need to include backslashes in a string (like in regex or file paths), use a raw string by adding an r before the quotes.
# Normal string interprets \n as newline
print("C:\new_folder")
# Raw string treats backslash as a character
print(r"C:\new_folder")