Basics

Strings in Python: split, replace, strip, join, Slicing and f-strings

Updated: · Skillaria.Top

A string in Python (the str type) is an immutable sequence of Unicode characters. The split() method breaks a string into a list, join() glues a list back together, replace() substitutes a substring and strip() removes spaces at the edges; each method returns a new string. The most convenient way to insert values is an f-string: f"{name}: {price:.2f}".

Strings are present in every Python program: user input, file names, CSV lines, API responses. The str type stores text in Unicode, so Cyrillic and emoji work without any setup. The most-used methods are split, replace, strip and join, and values are most conveniently printed with f-strings. Let us go through all of this with examples.

How a string works in Python

A string is written in single or double quotes — there is no difference: 'coffee' and "coffee" are the same. Triple quotes create a multiline string in which line breaks are kept as they are.

name = "Coffee"
note = """First line
Second line"""
print(len(name))  # 4 — the length of the string in characters

The main property of strings is immutability. A method does not change the string but returns a new one. So s.replace("a", "b") without an assignment does nothing — you must write s = s.replace("a", "b"). This is the most common beginner mistake.

Special characters, line breaks and raw strings

A line break is written \n, a tab as \t, a backslash as \\. The r prefix makes a string "raw": backslashes in it are not processed. This is handy for Windows paths and regular expressions.

print("Total:\n$350")
path = r"C:\new\table.csv"   # \n and \t will not become special characters

A long expression can be continued on the next line of code by enclosing it in brackets: adjacent string literals inside brackets are joined by Python automatically.

split: breaking a string into a list

The split() method divides a string by a delimiter and returns a list. Without an argument it cuts on any whitespace and ignores repeated spaces — which is handy for parsing commands.

"add  Coffee 250".split()      # ['add', 'Coffee', '250']
"2026-10-16".split("-")        # ['2026', '10', '16']
"a,b,,c".split(",")            # ['a', 'b', '', 'c']
"key=value=x".split("=", 1)    # ['key', 'value=x']

Note the difference: with an explicit delimiter, empty fragments are kept. The second argument maxsplit limits the number of cuts, and rsplit() cuts from the right. To split text into lines, use splitlines(): it understands both \n and \r\n and does not leave an empty element at the end.

text = "coffee\ntaxi\n"
text.split("\n")     # ['coffee', 'taxi', '']
text.splitlines()    # ['coffee', 'taxi']

join: gluing a list into a string

join() is the reverse operation. It is called on the delimiter string and receives a list of strings as its argument:

items = ["coffee", "taxi", "lunch"]
print(", ".join(items))   # coffee, taxi, lunch
print("\n".join(items))   # each item on a new line

All elements must be strings, otherwise you get TypeError: sequence item 0: expected str instance, int found. Convert numbers first: ", ".join(str(x) for x in amounts).

Concatenation and combining strings

Two strings can be added with + and repeated with *: "-" * 20. But gluing hundreds of fragments in a loop with += is slow, because each time a new string is created. Collect the parts in a list and join them with one join(). A string cannot be added to a number directly: "Total: " + 5 raises a TypeError; use the str() function or an f-string.

replace: substituting a substring

replace(old, new) replaces all occurrences of a substring. A third argument limits the number of replacements.

price = "1 250,50"
price = price.replace(" ", "").replace(",", ".")
print(float(price))                  # 1250.5

"a-b-c".replace("-", "+", 1)         # 'a+b-c'

The method is case-sensitive and looks for an exact match. For replacements by pattern (for example, "all digits") you need the re module and the re.sub() function.

strip, lstrip, rstrip: trimming a string

strip() removes spaces, tabs and line breaks from both ends. lstrip() trims only the left side, rstrip() only the right. This is the first thing to do with user input and with strings read from a file.

raw = "  Coffee \n"
raw.strip()       # 'Coffee'
raw.rstrip()      # '  Coffee'
"xxCoffeexx".strip("x")   # 'Coffee'

The argument is a set of characters, not a substring: "abcTextcba".strip("abc") removes all the a, b and c characters from the ends in any order. To cut off exactly a prefix or a suffix, use removeprefix() and removesuffix() (since Python 3.9).

Other useful string methods

MethodWhat it doesExample → result
lower(), upper()case"Coffee".lower() → 'coffee'
startswith(), endswith()check the start and end"a.csv".endswith(".csv") → True
find()position of a substring, or -1"coffee".find("f") → 3
count()number of occurrences"banana".count("a") → 3
isdigit()

FAQ

How do I find the length of a string in Python?

The function len(s) returns the number of characters. For Cyrillic and emoji, Unicode characters are counted, not bytes; the size in bytes is given by len(s.encode("utf-8")).

How do I convert a number to a string and back?

str(250) gives '250', and int("250") and float("2.5") do the reverse. If the string does not look like a number, int() raises ValueError, so input should be checked.

Why doesn't replace change my string?

Strings are immutable, and replace returns a new string. Assign the result: s = s.replace("a", "b").

How do I check whether a string is empty?

An empty string is false, so if not s: is enough. If the string may consist of spaces, check if not s.strip():.

How is a t-string different from an f-string?

An f-string immediately returns a finished str, while a t-string (Python 3.14+) is a Template object with separate text pieces and values. This allows data to be escaped safely for HTML and SQL.

Learn this topic on video

This topic is covered in depth with practice in the course “Python 3.15: от новичка до профи”.

Go to course