agyanadda@gmail.com

Python Strings

Python Basics 1 min read Updated Dec 4, 2026 Topic 7 of 32

A string (str) is text inside quotes: 'hi', "hi", or triple quotes for several lines.

Indexing and slicing

  • s[0] first character, s[-1] last
  • s[0:4] characters 0 to 3, s[::-1] reversed
  • len(s) length

Strings are immutable — methods return a new string.

Common methods

  • upper(), lower(), title(), capitalize()
  • strip() — remove spaces from both ends
  • replace("a", "b")
  • split(",") → list, ", ".join(list) → string
  • find("x"), count("x"), startswith(), endswith()
  • isdigit(), isalpha(), isalnum()
  • "py" in "python" → True

f-strings (formatting)

f"Hello {name}, total {amount:.2f}" — put expressions in {}. Format specs: :.2f (2 decimals), :, (thousands), :>10 (align), :% (percent).

Escape characters

\n new line, \t tab, \\ backslash, \" quote. Raw strings r"C:\new" ignore escapes.

Example

Example — String toolkit Python
text = "  learn python at agyanadda  "

clean = text.strip().title()
print(clean)                          # Learn Python At Agyanadda
print(clean[0:5], clean[-9:])         # Learn Agyanadda
print(len(clean), clean.count("a"))

csv = "pen,book,bag"
items = csv.split(",")
print(items, " | ".join(items))

name, marks, total = "Asha", 436, 500
print(f"{name} scored {marks}/{total} = {marks / total:.1%}")
print(f"{'Item':<10}{'Price':>8}")
print(f"{'Laptop':<10}{54999:>8,}")

print("Python"[::-1], "py" in "python")

Prints the cleaned title, slices, the list ['pen', 'book', 'bag'] and 'pen | book | bag', "Asha scored 436/500 = 87.2%", an aligned table row "Laptop 54,999", and nohtyP True.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does "Hello"[1:4] return?

Exercise 2 True / False

String methods like upper() change the original string.

Exercise 3 Fill in the Blank

Remove spaces from both ends with the ___() method.

Frequently Asked Questions

Use f-strings: they are the fastest and easiest to read. You will also see the older str.format() and % formatting in existing code.