String Handling in Python

    Kedar Kabra4 min readUpdated

    A string is text — anything wrapped in quotes. You can use single or double quotes, and Python gives you many tools to slice, search, and transform text:

    name = "Asha"
    city = 'Jalgaon'
    
    # f-strings let you drop variables right into text
    print(f"{name} lives in {city}")   # Asha lives in Jalgaon
    
    # Strings can be joined with +
    greeting = "Hello, " + name
    print(greeting)                    # Hello, Asha
    

    Let's cover the parts you'll use every day.

    Indexing and slicing

    A string is a sequence of characters, each with a position starting at 0. You can grab one character or a slice:

    text = "Python"
    
    print(text[0])      # P   (first character)
    print(text[-1])     # n   (last character)
    print(text[0:3])    # Pyt (characters 0, 1, 2 — stops before 3)
    print(text[2:])     # thon (from index 2 to the end)
    print(text[:4])     # Pyth (from start up to index 4)
    print(text[::-1])   # nohtyP (reversed!)
    

    Slicing [start:stop] includes the start index but stops before the stop index — the same rule as range().

    f-strings: the modern way to format

    f-strings (formatted string literals) are the cleanest way to build text with variables. Put an f before the quotes and write {expression} inside:

    name = "Ravi"
    score = 87.5
    
    print(f"{name} scored {score}%")              # Ravi scored 87.5%
    print(f"Half of the score is {score / 2}")    # Half of the score is 43.75
    
    # You can format numbers too: round to 1 decimal place
    print(f"Score: {score:.1f}")                  # Score: 87.5
    

    Useful string methods

    Strings come with dozens of built-in methods. Here are the ones beginners use most:

    text = "  Hello, World  "
    
    print(text.strip())          # "Hello, World"  (removes outer spaces)
    print(text.upper())          # "  HELLO, WORLD  "
    print(text.lower())          # "  hello, world  "
    print(text.replace("World", "Python"))  # "  Hello, Python  "
    
    sentence = "one two three"
    print(sentence.split())      # ['one', 'two', 'three']  (splits on spaces)
    
    words = ["a", "b", "c"]
    print("-".join(words))       # "a-b-c"  (joins a list into a string)
    
    print("Hello".startswith("He"))   # True
    print("apple".find("p"))           # 1  (position of first 'p')
    print(len("Python"))               # 6  (length of the string)
    

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Strings are immutable

    You cannot change a single character of a string in place — strings are immutable, like tuples. Methods like .replace() return a new string instead:

    text = "cat"
    # text[0] = "b"          # ERROR: strings can't be changed in place
    
    new_text = text.replace("c", "b")   # make a new string
    print(new_text)          # bat
    print(text)              # cat — the original is unchanged
    

    A practical example

    # Clean up and format a user's full name
    
    raw = "   ASHA  patil  "
    
    # strip outer spaces, fix the casing
    cleaned = raw.strip().title()    # .title() capitalises each word
    print(f"Welcome, {cleaned}!")    # Welcome, Asha  Patil!
    
    # Count words
    word_count = len(cleaned.split())
    print(f"Words in name: {word_count}")
    

    Common mistakes

    • Trying to change a string in place: text[0] = "x" raises a TypeError. Build a new string with a method like .replace().
    • Forgetting .strip() on user input: Stray spaces from input() cause comparisons like text == "yes" to fail. Clean input with .strip() first.
    • Mixing quote types wrongly: "He said "hi"" breaks. Use single quotes inside double quotes, or escape with \".
    • Using + to join a number: "Age: " + 25 raises a TypeError. Use an f-string or str(25).
    • Confusing .find() and .index(): .find() returns -1 if the substring is missing; .index() raises an error. Pick based on whether you want a crash or a sentinel.

    FAQ

    What's the difference between single and double quotes? None functionally. Use whichever avoids escaping — double quotes around text that contains an apostrophe, for instance.

    How do I write a multi-line string? Wrap it in triple quotes: """line one\nline two""". Everything between the triple quotes, including line breaks, becomes part of the string.

    Are f-strings the best way to format? For most cases, yes — they're readable and fast. They've been available since Python 3.6 and are the modern standard.


    Strings build on what you learned about Variables & Data Types in Python. For transforming many strings at once, see List Comprehensions in Python. More topics on the Python learning hub.

    Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Kedar Kabra

    Instructor, Infoplanet

    Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.

    Related guides