Strings in Python: Create, Use, and Format Text

To work with a name or message in a Python program, you need a value that represents text. Python uses strings, values of the built-in str type, to hold text.

I’ll show how to read and transform strings, then use f-strings to format values in text.

TL;DR

A Python string is immutable Unicode text, and you work with it by reading characters or creating a new string with an operation.

  • Use indexes and slices to read parts of text.
  • Use methods such as split(), strip() and replace() to transform text.
  • Use f-strings to place values in formatted output.

What is a string in Python?

A string is a sequence of text represented by the built-in str type. A literal can use either quote style, as in “don’t”.

name = 'Mina'
message = "Hello, " + name
note = """First line
Second line"""

A backslash escape such as \n represents a newline inside a regular literal.

For network protocols and binary file formats, use bytes and choose an explicit encoding when converting between bytes and text.

For a small concrete example, a filename extension can be checked with endswith(), and a prefix can be removed with removeprefix() on supported Python versions. Case conversion such as lower() can help with case-insensitive comparisons, but preserve the original spelling when it must be displayed back to a user.

How to work with strings in Python step by step

I ran the examples below from one Python file. Its output is shown in the terminal image beside the code.

Step 1: Read characters and slices by index

Use square brackets with a zero-based index for one character. Negative indexes count from the end, while a slice includes its start and excludes its stop.

text = "Python strings"
print(len(text))
print(text[0], text[-1])
print(text[7:])

The run printed this exact output:

14
P s
strings
Positive and negative indexes for each character in Hello
Positive and negative indexes select the same character positions from opposite ends.

The slice text[7:] starts at index 7 and continues to the end. Asking for an index outside the sequence raises IndexError, while a slice beyond the end is clipped rather than raising that error.

Step 2: Split, join, and transform text

With no argument, split() groups runs of whitespace. A supplied delimiter matches that exact text.

print("red,blue".split(","))
print(" / ".join(["red", "blue"]))

The same run returned [‘red’, ‘blue’] and red / blue. join() is called on the separator, and each item in its input must already be a string.

For other edits, strip() removes selected characters from the ends, replace() substitutes matching text, and lower() changes letter case.

raw = "  Red, blue  "
clean = raw.strip().lower().replace(",", " / ")
print(clean)

strip() affects the ends only, so normalize internal whitespace separately when that matters.

Step 3: Combine values with an f-string

An f-string starts with f and places an expression in braces.

name = "Mina"
print(f"Hello, {name}!")

The expression value appears in the result.

Step 4: Reverse or concatenate a string

A slice with a step of -1 reads characters in reverse order. The plus operator concatenates two strings, but repeated additions in a loop can be replaced with join() when combining many pieces.

text = "Python strings"
print(text[::-1])
print("Hello, " + "Mina")

The first expression returns sgnirts nohtyP. The reversed text appears in the output, followed by the concatenated greeting.

Step 5: Loop through each character

A for loop visits characters in order, which is useful when each character needs a separate check or transformation. Use enumerate() when the position matters as well as the character.

word = "cat"
for index, character in enumerate(word):
    print(index, character)

The loop prints one position and character per line. Iterating over a string does not split it into words, so call split() first when the unit of work is a word.

What string edge cases should you know?

Assigning to an individual character raises TypeError:

text = "cat"
text[0] = "b"

Construct a replacement from the parts around the changed character, or use replace() when the target text is known.

text = "cat"
text = "b" + text[1:]
print(text)

This prints bat.

len() counts Unicode code points, not necessarily the characters a person perceives as one symbol. A symbol such as an emoji may combine multiple code points.

Converting text to an integer requires numeric content. int(“42”) returns 42, while int(“42px”) raises ValueError. Trim surrounding whitespace first when the input format permits it, then handle invalid input with try/except.

For an empty string, len() is zero and every index is invalid, though a slice such as text[:] remains valid. For paths, use a path-specific module rather than splitting on a slash, since separators differ by platform.

For a dedicated walkthrough, read how to slice strings in Python and string concatenation in Python. The site’s Python f-string guide covers formatting detail.

Use multiline strings for text with line breaks

Triple quotes suit fixed templates or explanatory text that spans lines. Indentation in the source remains in the value, so align the closing delimiter when whitespace matters.

message = """First line
Second line"""
print(message.splitlines())

The result is a list with one entry for each line. Use splitlines() when line boundaries matter, rather than splitting on a single newline character, since text can use different line-ending conventions.

Strings are sequences, but not lists

The expression “py” in “python” is true because the left-hand substring occurs in the right-hand text. A list is a better choice when an algorithm needs assignable character positions.

letters = list("cat")
letters[0] = "b"
print("".join(letters))

The final line displays the joined characters. join() turns the list entries back into one string. For a known text replacement, replace() avoids this conversion.

Conclusion: choose the operation that fits

Choose indexing to read one position, slicing for a portion, and a method or formatting expression for transformed output. The official Python str documentation lists sequence behavior and methods, while the string module reference explains formatting tools.

FAQ

These answers cover common string questions that go beyond the examples above.

Are strings mutable in Python?

No. A string cannot be changed in place. Methods return a new string, which you can assign to a variable.

How do you find the length of a string?

Call len(text). It returns the number of Unicode code points in the string.

How do you convert a string to an integer?

Call int(text) when the text contains a valid integer representation. Invalid text raises ValueError.

What does an f-string do?

An f-string evaluates expressions inside braces and inserts their values into a string literal prefixed with f.