October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

Different Ways to Create Strings in Python

A practical guide to creating strings in Python: when to use literals, triple quotes, f-strings, str(), +, join(), or io.StringIO, with version notes.

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.

Python has several ways to create a string, and each one fits a different job. Use a quoted literal for fixed text, a triple-quoted literal for multiline text, an f-string when values belong inside the text, str() to convert a single object, + for a simple runtime combination, and ''.join(parts) or io.StringIO when you are assembling many fragments. The sections below explain each option, when it fits, and where it breaks.

Choosing a method at a glance

Most choices come down to four questions: is the text fixed or does it include runtime values, does it span lines or contain backslashes, are you combining two pieces or many, and which Python version does your code need to run on. The table compares the main approaches on those points.

Approach Fixed or runtime Multiline Best for Version requirement
Quoted literal ('...' or "...") Fixed No, single line Short constant text Any Python 3
Triple-quoted literal ("""...""") Fixed Yes Blocks of text, help messages, SQL or templates Any Python 3
Raw literal (r"...") Fixed Possible with triple quotes Regular expressions, Windows paths Any Python 3
Adjacent literals Fixed, joined in source code Yes, when split across lines in parentheses Long constant text split for readability Any Python 3
+ operator Runtime Only if the operands contain newlines Combining two or three values Any Python 3
f-string (f"...") Runtime Yes, with triple quotes Embedding values and expressions in text Python 3.6 and later
str.format() Runtime Yes Templates stored as strings and filled later Any Python 3
str() Runtime Not applicable Converting one object to text Any Python 3
str.join() Runtime Depends on separator Joining a list or other iterable of strings Any Python 3
io.StringIO Runtime Yes Writing many pieces incrementally Any Python 3

Literals: fixed text in source code

A string literal is text written directly in your source file. Python treats single quotes, double quotes, and triple quotes as equivalent ways to create a str value, and the language reference covers the full literal rules in the Python 3.14 lexical analysis reference.

Single and double quotes

Either quote style works. Pick one that matches the surrounding code, and use the other one when the text itself contains a quote, so you avoid escaping:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
single = 'Hello'
double = "Hello"
quoted = "It's ready"

Triple-quoted multiline literals

Triple quotes allow line breaks inside the literal, and the newlines and indentation between the delimiters become part of the value:

message = """First line
Second line"""

If you want the text to start after the opening delimiter without the first newline, put a backslash directly before that line break. The backslash removes the newline from the value, which makes the first line of the literal line up with the code around it.

Raw literals

A raw string, written with an r prefix, leaves backslashes as written instead of interpreting escape sequences such as n. This is most useful for regular expressions:

pattern = r"d{4}-d{2}-d{2}"

Raw strings still follow the quoting rules. A raw string cannot end with an odd number of backslashes, because the final backslash would escape the closing quote.

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

Adjacent literals, +, and *

These three operations combine text before or while your program runs. They look similar but work at different levels, so it helps to know which one is happening.

Adjacent literals are joined by the parser

Two or more string literals placed next to each other are concatenated during parsing. This is a source-code feature, not a runtime operation, and it is the cleanest way to split a long constant across lines:

message = (
    "Put several strings within parentheses "
    "to make a long literal easier to read."
)

Adjacency works only for literals. A variable next to a literal does not join with it, so name "is here" is a syntax error. Literal adjacency also cannot mix bytes and str literals.

The + operator

The + operator joins two strings at runtime. It works well for a small, fixed number of pieces:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
language = "Py" + "thon"
label = "Status: " + status

For many pieces, especially inside a loop, + creates a new string on each step. The built-in types reference points to str.join() and io.StringIO for building text from many fragments, covered in the section on joining below.

The * operator

The * operator repeats a string. It is useful for fixed patterns such as separators:

repeated = "ha" * 3
divider = "-" * 40

Building text from values

When a string contains values computed at runtime, you have three main tools: f-strings, str.format(), and str(). F-strings are usually the most readable choice for new code.

F-strings

An f-string is a string literal with an f prefix. Expressions inside braces are evaluated and inserted into the text:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
name = "Ada"
count = 3
message = f"{name} wrote {count} examples"

A format specification after a colon controls how a value is displayed. Here, .3f formats a float with three decimal places:

import math
message = f"pi is about {math.pi:.3f}"

The Python 3.13 tutorial on input and output demonstrates expression fields and numeric precision formatting with this syntax.

Adding = after an expression prints both the expression text and its value, which is handy while debugging: f"{count=}" produces count=3. This debug specifier was added in Python 3.8.

str.format() and format()

The str.format() method uses placeholders in a template and fills them with arguments. It is the better choice when the template is stored somewhere and filled in later, such as a configuration file or a translation catalog:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
template = "{} wrote {} examples"
message = template.format("Ada", 3)
price = format(12.5, ".2f")

The format specification mini-language used by str.format() and the built-in format() function is shared across these interfaces. The exact options depend on the type being formatted.

Converting one object with str()

str(object) returns a text representation of an object. It is the direct way to turn a number or other value into text before combining it:

count = 3
label = "count=" + str(count)

Bytes need care. Calling str() on a bytes object does not decode it. It returns the printed form of the bytes, so str(b"hi") gives "b'hi'". To decode bytes into text, pass an encoding, and optionally an error policy: str(data, "utf-8") or data.decode("utf-8"). Choose the encoding that matches the source of the bytes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Joining many fragments

When you have a list of pieces, build the result in one step instead of repeatedly adding strings together. The built-in types reference names str.join() and io.StringIO as ways to construct strings from multiple fragments, documented in the Python 3.12 built-in types reference.

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

Using str.join()

Call join() on the separator you want between the pieces:

parts = ["red", "green", "blue"]
colors = ", ".join(parts)   # "red, green, blue"
joined = "".join(parts)     # "redgreenblue"

All items must already be strings. A list containing numbers raises a TypeError until you convert each item, for example with ", ".join(str(n) for n in numbers).

Writing incrementally with io.StringIO

When the pieces arrive one at a time, or you want to write to a buffer the same way you would write to a file, use StringIO:

from io import StringIO

buffer = StringIO()
for part in parts:
    buffer.write(part)
result = buffer.getvalue()

Python strings are immutable, so each concatenation creates a new object. The documentation does not give a size threshold where one method becomes faster, so choose join() or StringIO for the pattern they express: a complete list of pieces, or a stream of writes.

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

Version and compatibility notes

Several string features depend on the Python version. The Python 3.14 lexical reference records these milestones:

  • F-strings were added in Python 3.6.
  • The debug specifier ({value=}) was added in Python 3.8.
  • Many earlier restrictions on expressions inside f-strings were removed in Python 3.12.
  • Template string literals (t"...") were added in Python 3.14.

If your code must run on Python 3.5 or older, avoid f-strings entirely. If it must run on Python 3.6 through 3.11, avoid reusing the same quote type inside an f-string expression, which the older parser rejects:

# Fails before Python 3.12
data = {"key": "value"}
print(f"{data["key"]}")

# Works in every version that supports f-strings
print(f"{data['key']}")

Template strings (t"...") return a template object rather than a str, so do not use them in code that must run on releases earlier than 3.14.

Common mistakes

  • Concatenating numbers with +. "count=" + 3 raises a TypeError. Use an f-string or str(3).
  • Expecting adjacency to work with variables. Only literals join at parse time. Use + or an f-string for variables.
  • Mixing bytes and text. A b"..." literal creates bytes, not str. Decode it before combining it with text.
  • Building large strings with repeated += in a loop. Collect the pieces in a list and call join(), or write to a StringIO buffer.

Which method should you use?

For fixed text, write a literal, using triple quotes when it spans lines. For text that includes values, use an f-string if your Python version supports it, and str.format() when the template must be defined separately from the data. Use str() to convert a single object, + for a short runtime combination, and join() or StringIO when assembling many pieces.

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

For reference material, the Python 3.14 expressions reference covers how concatenation and f-string expressions are evaluated.

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 *

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
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.