What You Will Learn
Beginner
- How to create and manipulate strings
- String methods (upper, split, replace, etc.)
- f-strings for formatting
Terminalpython
# Creating strings
name = "Anita"
city = 'Mumbai'
multi = """Multi
line
string"""
# String length
print(len(name)) # 5
# Indexing (0-based)
print(name[0]) # A
print(name[-1]) # a (last char)
# Slicing [start:end:step]
print(name[0:3]) # Ant
print(name[::-1]) # atinA (reverse!)String Methods
Terminalpython
text = " Hello, World! "
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.strip()) # "Hello, World!" (removes spaces)
print(text.replace("World", "Python")) # " Hello, Python! "
print(text.split(",")) # [" Hello", " World! "]
print(" ".join(["Hello", "World"])) # "Hello World"
print(text.find("World")) # 9 (index of first match)
print("abc".startswith("a")) # Truef-strings (Modern Formatting)
Terminalpython
name = "Anita"
age = 28
# f-string (Python 3.6+)
print(f"My name is {name} and I am {age} years old.")
# Expressions inside f-strings
print(f"{name.upper()} is {age + 1} next year.")
# Formatting numbers
price = 19.99
print(f"Price: ${price:.2f}") # Price: $19.99
print(f"{1000000:,}") # 1,000,000Always use f-strings
f-strings are the modern, fastest, and most readable way to format strings in Python. Avoid old methods like % formatting and .format() unless you need them.Practical Exercise
Create a string variable with your name
Print it reversed: name[::-1]
Convert to uppercase: name.upper()
Use an f-string: f"Hello, {name}!"
Split a sentence: "Hello World".split()
Key Takeaways
- Strings are immutable - methods return new strings.
- Indexing: s[0] is first, s[-1] is last.
- Slicing: s[start:end:step]. s[::-1] reverses.
- Key methods: upper, lower, strip, split, join, replace, find.
- f-strings: f"Hello, {name}!" - modern formatting.
Comments
Comments
Post a Comment