Python Strings Explained: Slicing, Methods and f-strings for Beginners

Python Part 5 – Strings in Depth (preview)

Python for Beginners – Part 5

Strings in Depth

Welcome back. Quick thing worth noticing, a string is really just a sequence of characters, the same way a list is a sequence of items. That means almost everything you learned about slicing and indexing lists last post works exactly the same way on strings too. Let's actually put that to proper use this time.

1. Indexing and slicing strings

indexing.py
name = "Diwakar"
print(name[0])      # D
print(name[-1])     # r, the last letter
print(name[0:3])    # Dim... wait, Diw

Same rules as lists, position 0 is the first character, negative numbers count from the end, and a slice's end position is never included. If that last sentence feels familiar, good, it's the third time this exact rule has shown up in this series.

2. Strings are immutable, and what that means

Analogy: a Python string is like a printed certificate, not a whiteboard. You can't erase one letter and write a new one in its place. If you want a changed version, you make an entirely new certificate, the original stays exactly as it was printed.
immutable.py
name = "Diwakar"
name[0] = "X"
# TypeError: 'str' object does not support item assignment

To actually change a string, you build a new one, often using slicing or methods, and store it, usually right back in the same variable name.

fixed.py
name = "Diwakar"
name = "X" + name[1:]
print(name)   # Xiwakar

3. Useful string methods

MethodWhat it does
len(s)Number of characters
s.upper() / s.lower()Converts case
s.strip()Removes leading and trailing spaces
s.replace(a, b)Replaces every occurrence of a with b
s.split(sep)Breaks a string into a list, using sep as the divider
s.find(sub)Position of the first match, or -1 if not found
s.count(sub)How many times sub appears

4. Formatting with f-strings

You've been joining text with + since Part 1, which works but gets clunky fast. An f-string lets you drop variables straight into text using curly braces.

fstrings.py
name = "Diwakar"
age = 25

# Old way
print("My name is " + name + " and I am " + str(age))

# f-string way
print(f"My name is {name} and I am {age}")
Notice: with f-strings you don't even need str() around the number, Python converts it for you automatically inside the curly braces. Put an f right before the opening quote, that's the whole trick.

5. The string lab

Try it: slice it, transform it

Type anything, drag the slice numbers, and click a method button.

s[ : ]
Click a method above to see the result.

6. Example 1 (Easy): Shout a name

shout.py
name = input("Enter your name: ")
print(name.upper() + "!!!")

7. Example 2 (Medium): Is it a palindrome?

A palindrome reads the same forwards and backwards, like "madam" or "nitin". Reversing a string in Python is a one-liner using the slice trick from the lab above.

palindrome.py
word = input("Enter a word: ").lower()

if word == word[::-1]:
    print("That's a palindrome!")
else:
    print("Not a palindrome.")

word[::-1] means "the whole string, stepping backwards," which simply reverses it. We compare that reversed version to the original, if they match exactly, it's a palindrome.

8. Example 3 (Harder): Counting vowels

count_vowels.py
text = input("Enter a sentence: ").lower()
vowels = "aeiou"
count = 0

for letter in text:
    if letter in vowels:
        count = count + 1

print("Vowel count:", count)

if letter in vowels checks whether a single character appears anywhere inside the string "aeiou", a clean, short way to ask "is this a vowel?"

9. Example 4 (Hero level): A tiny text analyzer

text_analyzer.py
sentence = input("Enter a sentence: ")
words = sentence.split()

print(f"Word count: {len(words)}")
print(f"Character count: {len(sentence)}")

for word in words:
    print(f"{word} backwards is {word[::-1]}")

sentence.split() breaks the sentence into a list of words wherever there's a space, turning Part 4's list skills and this post's string skills into one small, genuinely useful tool.

10. Common mistakes

  1. Trying to change a character directly, like s[0] = "X". Strings are immutable, build a new string instead.
  2. Forgetting f-strings need the letter f right before the quote, without it, the curly braces print literally.
  3. Case mismatches when comparing strings, "Python" and "python" are not equal unless you convert both with .lower() first.
  4. Slicing off-by-one, same exclusive-end rule as range() and lists.

11. Practice tasks

  1. Ask for a sentence and print it with every space replaced by an underscore.
  2. Write a palindrome checker that ignores spaces, so "nurses run" also counts.
  3. Count how many times a specific letter appears in a word, using .count().
  4. Challenge: write a program that capitalizes the first letter of every word in a sentence, without using any built-in method that already does this for you.

Strings and lists turn out to share almost all the same tricks, which is really the quiet lesson of this post. Next in the rotation, we're back to DBMS for Part 4, ALTER TABLE and constraints. After that, Python Part 6, functions.

— Diwakar

Comments