VMware ESXi and vSphere Cluster Management
Python Strings: Creating and Using Text Values
Learn how Python strings represent text, how to create them with quotes, use variables and print(), handle special characters, and avoid common string errors.
What Is a Python String?
A string is Python's data type for text. It is an ordered sequence of characters. A character can be a letter, digit, space, punctuation mark, or symbol.
Names, messages, sentences, labels, and descriptions are generally represented as strings:
name = 'Ava'
message = 'Welcome to Python'
label = 'Score'
Strings can contain numeral characters, but that does not make them numbers. '123' is a string, while 123 is an integer:
Both values might appear similar when displayed, but Python treats them differently. For example, adding an integer to a string directly causes a type error:
total = '5' + 2 # TypeErrorConvert values intentionally with int() or str() when needed.
Creating String Literals
A string literal is text written directly in source code and surrounded by quote characters. The quote characters are called delimiters: they mark where the string begins and ends.
Single-Quoted Strings
Use matching single quotes to create a string literal:
print('Hello, world!')Output:
Hello, world!Double-Quoted Strings
Matching double quotes create a string in the same basic way:
print("Hello, world!")This displays the same greeting. In ordinary cases, single-quoted and double-quoted literals produce the same string value. Choose a consistent style that makes your code easy to read.
Choosing Single or Double Quotes
The main practical reason to choose one quote style over the other is to include the opposite quote character without escaping it.
An apostrophe can appear naturally inside a double-quoted string:
car_description = "Mark's car"
print(car_description)Output:
Mark's carDouble quotation marks can appear naturally inside a single-quoted string:
quote = 'She said "hello".'
print(quote)Output:
She said "hello".Both approaches are correct. Consistency and readability matter more than choosing one delimiter universally. Many projects select one preferred style and use the other when it avoids an escape sequence.
Printing Strings
print() is a Python function that writes a value to standard output. You can pass it a literal:
print('Python uses strings for text.')You can also print text stored in a variable:
message = 'Welcome to Python'
print(message)Output:
Welcome to PythonThe quote delimiters are syntax used to create the value. They are not ordinarily part of the stored text, so print('Hello') displays Hello, not 'Hello'. To display quotation marks, include them as characters inside the string by choosing suitable delimiters or using escape sequences.
String Variables
A variable is a named reference used to store and later access a value. Assign a string to a clearly named variable with the equals sign:
person_name = 'Ava'
item_description = 'A blue notebook'
message = 'Your order is ready.'
print(person_name)
print(item_description)
print(message)Assignment does not display the value by itself. Passing the variable to print() retrieves and displays its stored text.
Triple-Quoted Strings and Multiline Text
A triple-quoted string is surrounded by three matching single quotes or three matching double quotes. A multiline string contains one or more line breaks and can include those line breaks directly in the source code.
message = '''First line
Second line'''
print(message)Output:
First line
Second lineThe same idea works with triple double quotes:
message = """First line
Second line"""
print(message)Triple quotes are also commonly used for documentation strings, called docstrings, but their important feature here is allowing multiline text.
Escape Characters and Escape Sequences
An escape character is the backslash character (\). Inside a string literal, a backslash begins an escape sequence: a notation that represents a special character or safely includes a delimiter.
For example, if a single-quoted string must contain an apostrophe, escape that apostrophe:
message = 'It\'s ready.'
print(message)Output:
It's ready.You can also escape a double quote inside a double-quoted string:
message = "She said \"hello\"."
print(message)Output:
She said "hello".Common Escape Sequences
Newline Escape Versus Triple Quotes
An explicit newline escape keeps the source code on one line:
message = 'First line
Second line'A triple-quoted literal places the line break directly in the source:
message = '''First line
Second line'''Both strings contain a line break. Use \n when a compact one-line literal is clearer, and triple quotes when writing multiline content directly is more readable.
Raw Strings
A raw string, written with a prefix such as r, reduces the special meaning of backslashes. Raw strings can be convenient for Windows-style paths or regular expressions:
path = r'C:\Users\Ava\Documents'Raw strings are an optional tool, not a replacement for all escaping. They still follow string syntax rules and are not appropriate whenever you need ordinary escape sequences such as \n to be interpreted as line breaks.
Running String Examples
Interactive Python Shell
The Python interactive shell runs short expressions immediately, which makes it useful for experimenting:
print('Hello, world!')
print("Mark's car")Python Script
Place assignments and print statements in a file such as strings_example.py, then run it from a terminal:
python strings_example.pyThe exact command can vary by operating system; some systems use python3 instead of python.
Common Beginner Errors
Unterminated or Mismatched Strings
An unterminated string is missing its closing delimiter. Opening and closing delimiters must also match:
message = 'Hello" # IncorrectUse matching delimiters:
message = 'Hello'
message = "Hello"Python reports a syntax error when it reaches the end of the line or file without finding the expected closing quote.
An Unescaped Delimiter Ends the String Early
This code fails because Python interprets the apostrophe in It's as the closing single quote:
message = 'It's ready.' # IncorrectFix it by changing the outside delimiter:
message = "It's ready."Or escape the apostrophe:
message = 'It\'s ready.'Putting a Normal String Across Source Lines
A normal single-quoted or double-quoted literal cannot contain an unescaped source-code line break:
message = 'First line
Second line' # Incorrect if the line break is typed literallyUse a newline escape on one source line:
message = 'First line
Second line'Or use a triple-quoted literal:
message = '''First line
Second line'''Expecting Delimiters in Output
In print('Hello'), the quotes define the literal but are not stored as part of its text. If quotation marks should appear in the output, include them explicitly:
print('She said "Hello".')
print("She said \"Hello\".")Confusing Digit Characters with Numbers
Quotation marks determine the type:
text_number = '42'
number = 42
print(text_number)
print(number)Both may display as 42, but text_number is text and number is an integer. Use int(text_number) for intentional numeric conversion, or str(number) when you need to build text.
Next Steps
After learning to create strings, continue with string operations and related Python text topics, including indexing, slicing, concatenation, formatted strings, methods, and type conversion.