Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 1 - Python Fundamentals Python Python Basics Python Programming: From Zero to Real-World Applications

Strings and String Methods in Python

Reviewed & accurate
AI Summary

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"))  # True

f-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,000
Always 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.
Previously: Lesson 06 covered numbers.
Today: You learned: Master strings - the text type in Python.
Next: Lesson 08 covers input/output.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments