SwadhyAI Notes

All Python notes

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

python
# 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:

python
a = "Hello"
a[0] = "J"  # TypeError: 'str' object does not support item assignment

โœ… The Solution: Create a New String

python
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.

python
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

python
name = "John"
age = 36
txt = f"My name is {name}, and I am {age} years old."
print(txt)

๐Ÿ› ๏ธ Useful String Methods

Modify

python
a = " Hello "
print(a.strip())  # "Hello" (Removes whitespace)
print(a.lower())  # " hello "
print(a.upper())  # " HELLO "
print(a.replace("H", "J")) # " Jello "

Search & Split

python
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.

python
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.

python
# Normal string interprets \n as newline
print("C:\new_folder") 

# Raw string treats backslash as a character
print(r"C:\new_folder")