What is a string?
A string (str) is text inside quotes. Single, double and triple quotes all make strings.
city = "Ranchi"
grade = 'A'
address = """House 12,
Main Road""" # triple quotes keep line breaks
len() gives the number of characters, spaces included: len("Hi there") is 8.
Indexing: every character has a position
Positions start at 0. Negative positions count from the end.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
word = "Python"
print(word[0]) # P
print(word[-1]) # n (last character)
print(word[10]) # IndexError: string index out of range
Slicing: cut out part of a string
text[start:stop:step] takes characters from start up to, but not including, stop.
word = "Python"
print(word[0:3]) # Pyt
print(word[2:]) # thon (to the end)
print(word[:4]) # Pyth (from the start)
print(word[::2]) # Pto (every second character)
print(word[::-1]) # nohtyP (reversed)
Slicing never gives an IndexError; out-of-range limits are simply cut down to fit.
Strings cannot be changed
Strings are immutable: you cannot change one character in place.
name = "riya"
name[0] = "R" # TypeError
name = "R" + name[1:] # make a new string instead: "Riya"
Useful string methods
Every method returns a new string; the original stays the same.
| Method | Example | Result |
|---|---|---|
upper() / lower() | "Hi".upper() | "HI" |
title() | "asha rani".title() | "Asha Rani" |
strip() | " hi ".strip() | "hi" |
replace(a, b) | "9-9-9".replace("-", "/") | "9/9/9" |
find(x) | "banana".find("n") | 2 (or -1 if not found) |
count(x) | "banana".count("a") | 3 |
startswith(x) | "Mr Roy".startswith("Mr") | True |
isdigit() | "2026".isdigit() | True |
isalpha() | "abc1".isalpha() | False |
A common pattern is to chain methods to clean what a user typed:
email = " Asha.Roy@Gmail.COM ".strip().lower()
print(email) # asha.roy@gmail.com
split() and join()
split() breaks a string into a list; join() glues a list back into a string.
line = "Asha,91,Ranchi"
parts = line.split(",") # ['Asha', '91', 'Ranchi']
words = "learn python today".split() # splits on spaces
print("-".join(["10", "05", "2026"])) # 10-05-2026
f-strings: mix text and values
Put f before the quotes and write variables inside {}.
name = "Asha"
marks = 91.456
print(f"{name} scored {marks:.1f} marks") # Asha scored 91.5 marks
print(f"Next year: {2026 + 1}") # any expression works
Formatting inside f-strings
| Format | Meaning | Example | Result |
|---|---|---|---|
:.2f | 2 decimal places | f"{3.14159:.2f}" | 3.14 |
:, | thousands commas | f"{1500000:,}" | 1,500,000 |
:<10 | left-align in 10 spaces | f"{'Tea':<10}" | Tea |
:>8 | right-align in 8 spaces | f"{45:>8}" | 45 |
:^9 | centre in 9 spaces | f"{'Hi':^9}" | Hi |
Alignment is how you print neat bills and tables:
print(f"{'Item':<10}{'Price':>8}")
print(f"{'Tea':<10}{10:>8}")
print(f"{'Samosa':<10}{15:>8}")
Escape characters and the in operator
| Code | Meaning |
|---|---|
\n | new line |
\t | tab |
\\ | a backslash |
\' and \" | a quote inside a string |
in checks whether one string is inside another:
print("py" in "python") # True
print("@" not in "abc.com") # True
Example: mask a mobile number
mobile = "9876543210"
masked = "X" * 6 + mobile[-4:]
print(masked) # XXXXXX3210
Common mistakes
- Starting to count at 1: the first character is
text[0]. - Expecting
text.upper()to changetext. Store the result:text = text.upper(). - Forgetting the
fin an f-string:"{name}"prints the braces as they are. - Joining a string and a number with
+:"Age " + 15is aTypeError; use an f-string.
Key points
- Indexes start at 0; negative indexes count from the end.
text[a:b]stops just beforeb;text[::-1]reverses.- Strings are immutable, so methods return new strings.
- f-strings with format codes like
:.2fand:<10give clean output.
Practice questions
1. For s = "Jharkhand", what are s[0], s[-1] and s[1:4]?
J, d and har.
2. Write code that checks whether a word is a palindrome.
word = input("Word: ").lower()
print(word == word[::-1])3. Count the number of words in a sentence typed by the user.
sentence = input("Sentence: ")
print(len(sentence.split()))4. What does f"{7/3:.3f}" produce?
2.333.
5. Turn the string "2026-10-29" into "29/10/2026".
y, m, d = "2026-10-29".split("-")
print(f"{d}/{m}/{y}")