Skip to content
Laviyx Learn

Try

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.

Beginner8 min readUpdated
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:

Python
greeting = 'Hello'
name = "Asha"
poem = """Roses are red,
Violets are blue."""
print(poem)
Output
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:

Python
path = r"C:\new\folder"
print(path)
Output
C:\new\folder

Without 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:

CharacterPython
Index012345
Negative-6-5-4-3-2-1
Python
s = "Python"
print(s[0], s[-1], s[1:4], s[:2], s[2:], s[::-1])
print(len(s))
Output
P n yth Py thon nohtyP
6

A 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:

Python
s = "Python"
s[0] = "J"
Output
TypeError: 'str' object does not support item assignment

Instead, build a new string:

Python
s = "Python"
s = "J" + s[1:]
print(s)
Output
Jython

Every string method also returns a new string; the original is never modified.

Combining strings#

Python
print("ha" * 3, "a" + "b", "py" in "python")
Output
hahaha ab True

+ joins, * repeats, and in checks for a substring.

Essential methods#

Python
text = "  Learn Python, Build Projects  "
print(text.strip())
print(text.lower())
print(text.upper())
print(text.strip().title())
print(text.replace("Python", "SQL"))
Output
Learn Python, Build Projects
  learn python, build projects  
  LEARN PYTHON, BUILD PROJECTS  
Learn Python, Build Projects
  Learn SQL, Build Projects  
Python
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"))
Output
Learn python step by step
Learn Python Step By Step
3 6 -1
True True

find() returns the index of the first match, or -1 if there is none.

MethodReturns
strip(), lstrip(), rstrip()copy without surrounding whitespace
lower(), upper(), title(), capitalize()copy with changed case
replace(old, new)copy with every old replaced
find(sub) / index(sub)position of sub (index raises an error if missing)
count(sub)number of occurrences
startswith(x), endswith(x)True / False
split(sep)list of parts
sep.join(list)one string from a list

split and join#

split() breaks a string into a list; join() does the reverse:

Python
csv = "Asha,21,Pune"
parts = csv.split(",")
print(parts)
print(" | ".join(parts))
print("one two  three".split())
Output
['Asha', '21', 'Pune']
Asha | 21 | Pune
['one', 'two', 'three']

With no argument, split() splits on any run of whitespace.

Checking content#

Python
print("42".isdigit(), "abc".isalpha(), "abc123".isalnum(), "   ".isspace())
Output
True True True True

These are useful for validating user input.

f-string formatting#

f-strings can format values inside the braces with a : followed by a format spec:

Python
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%}")
Output
Asha scored 92.5
      Asha|
Asha      |
   Asha   |
1,234,567
25.6%
SpecMeaning
.1f1 decimal place
>10, <10, ^10right / left / centre in 10 characters
,thousands separator
.1%percentage with 1 decimal

A practical example#

Python
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())
Output
11 9 quick
The Quick Brown Fox Jumps Over The Lazy Dog

max(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
Python
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"))
Output
True True False

Key takeaway#

Finished this lesson?