Python course menu
Python Strings: Indexing, Slicing, Methods and f-strings
A complete beginner guide to Python strings: creating strings, indexing and slicing, immutability, essential string methods (strip, split, join, replace, find), f-string formatting, and checking content.
On this page
Text is everywhere: names, messages, emails, file contents, web pages. In Python, text is stored as a string (str): an ordered sequence of characters. This lesson covers everything you need to work with strings comfortably.
Creating strings#
Use single, double or triple quotes:
greeting = 'Hello'
name = "Asha"
poem = """Roses are red,
Violets are blue."""
print(poem)Roses are red,
Violets are blue.Triple quotes allow strings that span several lines. A raw string (prefix r) treats backslashes literally, which is handy for Windows paths and regular expressions:
path = r"C:\new\folder"
print(path)C:\new\folderWithout the r, \n would become a new line.
Indexing and slicing#
Each character has a position, starting at 0. Negative positions count from the end:
s = "Python"
print(s[0], s[-1], s[1:4], s[:2], s[2:], s[::-1])
print(len(s))P n yth Py thon nohtyP
6A slice s[start:stop] includes start but not stop. s[::-1] steps backwards through the whole string, reversing it.
Strings are immutable#
You cannot change a character in place:
s = "Python"
s[0] = "J"TypeError: 'str' object does not support item assignmentInstead, build a new string:
s = "Python"
s = "J" + s[1:]
print(s)JythonEvery string method also returns a new string; the original is never modified.
Combining strings#
print("ha" * 3, "a" + "b", "py" in "python")hahaha ab True+ joins, * repeats, and in checks for a substring.
Essential methods#
text = " Learn Python, Build Projects "
print(text.strip())
print(text.lower())
print(text.upper())
print(text.strip().title())
print(text.replace("Python", "SQL"))Learn Python, Build Projects
learn python, build projects
LEARN PYTHON, BUILD PROJECTS
Learn Python, Build Projects
Learn SQL, Build Projects title = "learn python step by step"
print(title.capitalize())
print(title.title())
print(title.count("p"), title.find("python"), title.find("java"))
print(title.startswith("learn"), title.endswith("step"))Learn python step by step
Learn Python Step By Step
3 6 -1
True Truefind() returns the index of the first match, or -1 if there is none.
split and join#
split() breaks a string into a list; join() does the reverse:
csv = "Asha,21,Pune"
parts = csv.split(",")
print(parts)
print(" | ".join(parts))
print("one two three".split())['Asha', '21', 'Pune']
Asha | 21 | Pune
['one', 'two', 'three']With no argument, split() splits on any run of whitespace.
Checking content#
print("42".isdigit(), "abc".isalpha(), "abc123".isalnum(), " ".isspace())True True True TrueThese are useful for validating user input.
f-string formatting#
f-strings can format values inside the braces with a : followed by a format spec:
name = "Asha"
score = 92.456
print(f"{name} scored {score:.1f}")
print(f"{name:>10}|")
print(f"{name:<10}|")
print(f"{name:^10}|")
print(f"{1234567:,}")
print(f"{0.256:.1%}")Asha scored 92.5
Asha|
Asha |
Asha |
1,234,567
25.6%A practical example#
sentence = "the quick brown fox jumps over the lazy dog"
vowels = sum(1 for ch in sentence if ch in "aeiou")
words = sentence.split()
longest = max(words, key=len)
print(vowels, len(words), longest)
print(sentence.title())11 9 quick
The Quick Brown Fox Jumps Over The Lazy Dogmax(words, key=len) returns the first longest word ("quick", "brown" and "jumps" all have 5 letters).
Common mistakes#
Practice#
Practice exercise
Write a function is_palindrome(text) that returns True if the text reads the same forwards and backwards, ignoring case, spaces and punctuation. Test it on "Madam", "A man, a plan, a canal: Panama" and "Python".
Show hint
Keep only characters where ch.isalnum() is true, lowercase them, then compare the result with its reverse [::-1].
Show solution
def is_palindrome(text):
cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
return cleaned == cleaned[::-1]
print(is_palindrome("Madam"),
is_palindrome("A man, a plan, a canal: Panama"),
is_palindrome("Python"))True True FalseKey takeaway#
Finished this lesson?