Python Strings & Methods
A string is a piece of text: a name, a URL, a log line, a whole file. Python strings come with dozens of built-in methods, and knowing the common ones will save you from writing loops for everyday text work.
- Create strings with any quote style
- Index and slice text
- Use the most common string methods
- Split text into parts and join it back
Create a string
Use single or double quotes; they mean the same thing. Pick the one that avoids escaping quotes inside the text. Triple quotes allow several lines.
a = 'single quotes'b = "double quotes, with an 'apostrophe' inside"c = """Line oneLine two"""print(a)print(b)print(c)print(len(c))single quotes double quotes, with an 'apostrophe' inside Line one Line two 17
A raw string, written r"...", ignores backslash escapes. It is handy for Windows paths and regular expressions:
print("C:\new\table") # \n and \t become a newline and a tabprint(r"C:\new\table") # printed exactly as writtenC: ew able C:\new\table
Index and slice
Strings are sequences of characters, so they support the same indexing and slicing as lists.
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| text | P | Y | T | H | O | N |
| negative | -6 | -5 | -4 | -3 | -2 | -1 |
text = "PYTHON"print(text[0], text[-1])print(text[0:2], text[2:], text[:-2])print(text[::2]) # every second characterprint(text[::-1]) # reversedP N PY THON PYTH PTO NOHTYP
Strings are immutable
You cannot change a character in place. Methods return a new string and leave the original alone.
word = "python"upper_word = word.upper()print(word, upper_word)word[0] = "P"python PYTHON
Traceback (most recent call last):
File "main.py", line 4, in <module>
word[0] = "P"
~~~~^^^
TypeError: 'str' object does not support item assignmentTo “change” a string, build a new one and assign it: word = "P" + word[1:].
Change case
title = "pYthon tUTORIAL"print(title.upper())print(title.lower())print(title.title())print(title.capitalize())print(title.swapcase())PYTHON TUTORIAL python tutorial Python Tutorial Python tutorial PyTHON Tutorial
Search inside a string
log = "ERROR 2026-11-02 login failed for user asha"print("failed" in log)print(log.startswith("ERROR"), log.endswith(".py"))print(log.find("login")) # index of the first matchprint(log.find("logout")) # -1 when not foundprint(log.count("a"))True True False 17 -1 3
find() returns -1 when the text is missing, while index() raises ValueError. Use in when you only need yes or no.
Clean up text
raw = " Pune, Maharashtra \n"print(repr(raw.strip()))print(repr(raw.lstrip()), repr(raw.rstrip()))print("--report--".strip("-"))print("2026-11-02".replace("-", "/"))print("aaa".replace("a", "b", 2)) # only the first 2'Pune, Maharashtra' 'Pune, Maharashtra \n' ' Pune, Maharashtra' report 2026/11/02 bba
Split and join
split() breaks a string into a list. join() does the opposite: it glues a list of strings together with the string you call it on.
csv_line = "asha,tester,pune"fields = csv_line.split(",")print(fields) sentence = " learn python step by step "words = sentence.split() # no argument: split on any run of whitespaceprint(words) print(" ".join(words))print("-".join(["2026", "11", "02"]))print(list("abc"))['asha', 'tester', 'pune'] ['learn', 'python', 'step', 'by', 'step'] learn python step by step 2026-11-02 ['a', 'b', 'c']
Check what a string contains
for s in ["2026", "python", "Py3", " ", "3.5"]: print(repr(s).ljust(9), s.isdigit(), s.isalpha(), s.isalnum(), s.isspace())'2026' True False True False 'python' False True True False 'Py3' False False True False ' ' False False False True '3.5' False False False False
The columns are isdigit(), isalpha(), isalnum() and isspace(). Note that "3.5".isdigit() is False because . is not a digit.
Alignment and padding
for name, score in [("Asha", 91), ("Ravi", 7), ("Meenakshi", 100)]: print(name.ljust(10), str(score).rjust(4), str(score).zfill(5))print("menu".center(20, "*"))Asha 91 00091 Ravi 7 00007 Meenakshi 100 00100 ********menu********
Common string methods
| Method | Returns |
|---|---|
upper(), lower(), title() | Text in a different case |
strip(), lstrip(), rstrip() | Text without surrounding whitespace (or given characters) |
replace(old, new) | Text with every old replaced |
split(sep) | A list of parts |
sep.join(items) | One string from a list of strings |
find(sub) / index(sub) | Position of sub (-1 / error if missing) |
count(sub) | How often sub appears |
startswith(x) / endswith(x) | True or False |
isdigit(), isalpha(), isalnum() | True or False |
ljust(), rjust(), center(), zfill() | Padded text |
Loop over a string
word = "level"vowels = 0for ch in word: if ch in "aeiou": vowels += 1print("vowels:", vowels)print("palindrome:", word == word[::-1])vowels: 2 palindrome: True
Check your understanding
Predict the output
s = "Hello, World"print(s[7:], s.lower().count("l"), s.split(", "))World 3 ['Hello', 'World']
s[7:] starts at index 7, the “W”. There are three l characters once everything is lower case. Splitting on ", " gives two parts.
Quick quiz
1. What does "python"[1:4] return?
The slice starts at index 1 and stops before index 4.
2. What does "a-b-c".split("-") return?
split() always returns a list of strings.
3. Why does name[0] = "J" fail?
Strings cannot be changed in place. Build a new one: "J" + name[1:].
4. Which returns -1 when the text is not found?
index() raises ValueError instead; count() returns 0.
Exercise: initials and username
From a full name, print the initials in upper case and a username made of the lower-case first name and the length of the full name.
" meena ravi kumar "
MRK meena16
Hint 1
split() without arguments handles the extra spaces.
Hint 2
"".join(...) can build the initials from a list.
full_name = " meena ravi kumar "parts = full_name.split() initials = "".join(p[0].upper() for p in parts)username = parts[0].lower() + str(len(" ".join(parts)))print(initials)print(username)MRK meena16
split() drops all the extra spaces, giving three clean words. " ".join(parts) rebuilds the tidy name “meena ravi kumar”, whose length is 16.
Program Practice
106 Python String Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python strings FAQ
How do I reverse a string in Python?
Use slicing with a step of -1: text[::-1]. "".join(reversed(text)) also works.
How do I check if a string contains a substring?
Use in: "py" in "python" is True. Use find() when you also need the position.
Are Python strings mutable?
No. Every method returns a new string. To change a variable, assign the new string to it: name = name.strip().
What is the difference between split() and split(” “)?
split() splits on any run of whitespace and ignores leading and trailing spaces. split(" ") splits on every single space, so repeated spaces give empty strings.