October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Python strings: How do literals, slicing, and formatting work?

Python’s str type stores text as an immutable sequence. Learn string literals, indexing, slicing, common methods, formatting, and how str differs from bytes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Python, a string is text stored as a str value. You can write strings with quotes, inspect them with indexing and methods, and build messages with f-strings or str.format(). A str is not the same as bytes: choose the former for text and the latter for byte-oriented data.

What is a Python string?

Python’s built-in str type represents text. The Python 3.14.7 documentation describes strings as “immutable sequences of Unicode code points.” In practice, a string is an ordered sequence you can inspect or derive new values from, but you cannot change its individual contents in place. Python 3.14.7 Built-in Types

As an Amazon Associate I earn from qualifying purchases.

For example, indexing and slicing select parts of a string, while operations such as case conversion return a result. They do not edit the original value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you write string literals?

Single and double quotes both create strings. Choose the delimiter that makes the text easiest to read; if the text contains that delimiter, escape it with a backslash or use the other quote style.

greeting = "Hello, Python"
message = 'It's a string, too.'
quoted = "She said, "Hello.""

Backslash escapes can represent characters such as a newline. Triple quotes allow a literal to span multiple lines. A raw-string prefix is useful when backslashes should generally remain as written, such as in a pattern, but it does not cancel every restriction in Python’s string-literal syntax.

line = "First linenSecond line"
notes = """First line
Second line"""
pattern = r"d+"

The rules for quotes, escapes, raw literals, and formatted string literals are described in the Python 3.14.8 language reference.

How do indexing, slicing, and methods work?

Indexing selects one position; slicing selects a range. Python indexes from zero, and a slice’s ending position is excluded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
language = "Python"
first = language[0]       # 'P'
part = language[1:4]      # 'yth'

String methods produce values you can assign or use immediately. The variable name below remains unchanged after upper().

name = "Ada Lovelace"
shout = name.upper()                 # 'ADA LOVELACE'
clean = "  hello  ".strip()          # 'hello'
position = name.find("Love")        # 4

Common tasks include searching with methods such as find(), changing case with lower() or upper(), and removing surrounding whitespace with strip(). Because strings are immutable, these methods return results rather than modifying the string on which they are called. The built-in types reference documents string operations and methods.

Indexing and slicing work on Unicode code points. The number returned by len(text) therefore should not automatically be treated as the number of characters a person perceives: combining marks and emoji sequences can affect that interpretation.

How do you put values into a string?

For a message with values already available in the surrounding code, an f-string puts expressions inside braces in the string literal. str.format() instead uses replacement fields in a format string and receives values through a method call.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
name = "Ada"
message = f"Hello, {name}!"

count = 3
summary = "Items: {}".format(count)

Both approaches support formatting details such as alignment, width, padding, precision, and numeric presentation. For example, a format specification can reserve a field width or set decimal precision:

score = 7.5
label = f"Score: {score:6.2f}"

With str.format(), replacement fields can also use conversions such as !s, !r, and !a. The Python format-string syntax reference explains fields and format specifications. The Python documentation notes that str.format() and the Formatter class share format-string syntax, though Formatter subclasses can define their own syntax. Python 3.14.8 Common string operations

Choose f-strings for inline expressions

Use an f-string when the values belong alongside the message in the same code. Its braces contain expressions evaluated in the context of the literal, which can make a short, local message easy to read.

Choose str.format() for a separate format string

Use str.format() when separating the template from supplied values is useful, such as when a format string is reused. Its replacement fields make that separation explicit. Neither approach is universally better; choose based on where the template and values need to live.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What is the difference between str and bytes?

str represents text; bytes represents a sequence of bytes. They are distinct Python types, so the practical choice is whether the value is human-readable text or byte-oriented data. Do not treat a Python 3 string as an ordinary encoded byte array.

text = "Hello"          # str
raw = b"Hello"          # bytes

For text handling, work with str. For data that is inherently byte-based, such as a byte sequence, use bytes. The distinction is documented in the Python built-in types reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.