Python Tutorial › Strings › Strings & Methods

Python Strings & Methods

BeginnerLesson 16 of 4714 min read11 runnable examples

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.

Advertisement
In this lesson
  • 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.

Python
a = 'single quotes'b = "double quotes, with an 'apostrophe' inside"c = """Line oneLine two"""print(a)print(b)print(c)print(len(c))
Output
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:

Python
print("C:\new\table")      # \n and \t become a newline and a tabprint(r"C:\new\table")     # printed exactly as written
Output
C:
ew	able
C:\new\table

Index and slice

Strings are sequences of characters, so they support the same indexing and slicing as lists.

Python
text = "PYTHON"print(text[0], text[-1])print(text[0:2], text[2:], text[:-2])print(text[::2])       # every second characterprint(text[::-1])      # reversed
Output
P 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.

Python
word = "python"upper_word = word.upper()print(word, upper_word)word[0] = "P"
Output
python PYTHON
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    word[0] = "P"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

To “change” a string, build a new one and assign it: word = "P" + word[1:].

Change case

Python
title = "pYthon tUTORIAL"print(title.upper())print(title.lower())print(title.title())print(title.capitalize())print(title.swapcase())
Output
PYTHON TUTORIAL
python tutorial
Python Tutorial
Python tutorial
PyTHON Tutorial
Python
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"))
Output
True
True False
17
-1
3
Tip

find() returns -1 when the text is missing, while index() raises ValueError. Use in when you only need yes or no.

Clean up text

Python
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
Output
'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.

Python
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"))
Output
['asha', 'tester', 'pune']
['learn', 'python', 'step', 'by', 'step']
learn python step by step
2026-11-02
['a', 'b', 'c']

Check what a string contains

Python
for s in ["2026", "python", "Py3", "  ", "3.5"]:    print(repr(s).ljust(9), s.isdigit(), s.isalpha(), s.isalnum(), s.isspace())
Output
'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

Python
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, "*"))
Output
Asha         91 00091
Ravi          7 00007
Meenakshi   100 00100
********menu********

Common string methods

MethodReturns
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

Python
word = "level"vowels = 0for ch in word:    if ch in "aeiou":        vowels += 1print("vowels:", vowels)print("palindrome:", word == word[::-1])
Output
vowels: 2
palindrome: True

Check your understanding

Predict the output

s = "Hello, World"print(s[7:], s.lower().count("l"), s.split(", "))

Quick quiz

1. What does "python"[1:4] return?

2. What does "a-b-c".split("-") return?

3. Why does name[0] = "J" fail?

4. Which returns -1 when the text is not found?

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.

Input
"  meena  ravi  kumar "
Expected output
MRK
meena16
Hint 1

split() without arguments handles the extra spaces.

Hint 2

"".join(...) can build the initials from a list.

Program Practice

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.