VMware ESXi and vSphere Cluster Management
Python Strings
Learn how Python strings represent text, how to create and print them, combine them, inspect their types, and convert numeric text for arithmetic.
What Is a String?
A string is Python's data type for text. A string represents an ordered sequence of characters. A character can be a letter, digit, space, punctuation mark, or other text unit.
For example, Hello contains five characters in a specific order. A variable can refer to a string value. A variable is a name that refers to a value.
message = 'Hello world!'
print(message)
Here, message is the variable name, while 'Hello world!' is the string value stored in, or referenced by, that variable. The print() function displays the value.
Creating String Literals
A string literal is text written directly in Python source code and enclosed by quotation marks. Python supports both single quotes and double quotes. Either style creates a value of type str.
greeting = 'Hello world!'
another_greeting = "Hello world!"
print(greeting)
print(another_greeting)
Both variables refer to strings containing the same text. The quotation marks delimit the literal in your source code; they are not normally displayed as part of the string.
Assigning Strings to Variables
Assignment uses the = operator to bind a variable name to a value.
name = 'Amina'
message = 'Welcome, ' + name
print(message)
In this example, name and message are variable names. The text between quotes is string data. The assignment operator does not mean that the variable name and the text are the same thing; it makes the name refer to the value.
Choosing Single or Double Quotes
Python supports both quote styles so that text can contain one kind of quote without extra syntax. Choose the delimiter that does not conflict with the content.
| String delimiter | Suitable content | Example |
|---|---|---|
| Single quotes | Text containing an apostrophe-free phrase or double quotation marks | 'She said "hello".' |
| Double quotes | Text containing an apostrophe | "Mark's car" |
| Escaped matching quote | Text that must contain the same quote used as the delimiter | 'Mark\'s car' |
description = "Mark's car"
print(description)
quote = 'She said "hello".'
print(quote)
A matching, unescaped quote ends a string literal. For example, 'Mark's car' is parsed as a string ending after Mark, followed by unexpected text, so it produces a syntax error.
You can use a backslash as an escape character. A backslash inside a string literal gives special meaning to the following character, including a matching quote.
description = 'Mark\'s car'
print(description)
The displayed result is Mark's car. In many cases, choosing the other quote style is easier to read.
Quoted Digits Are Still Text
Quotation marks determine the type of a literal. The value '5' is a string, while 5 is an integer. Their visible content may look similar, but Python treats them differently.
text_value = '5'
number_value = 5
print(type(text_value))
print(type(number_value))
type() inspects the type of a value. The output is similar to:
<class 'str'>
<class 'int'>
An integer is a whole-number value represented by the int type. A string containing digits is still text until you convert it.
String Concatenation with +
Concatenation means joining strings end to end. The + symbol is an operator: it performs an operation on values. When both operands are strings, it concatenates them rather than performing arithmetic.
x = '5'
y = '3'
print(x + y)
The result is 53, not 8, because the characters from the second string are placed after the characters from the first string.
| Expression | Type | Meaning | Result when used with + |
|---|---|---|---|
'5' | str | Text containing one digit character | Can concatenate with another string |
5 | int | The whole number five | Participates in numeric addition |
'5' + '3' | str | Two strings joined in sequence | '53' |
5 + 3 | int | Two integers added arithmetically | 8 |
int('5') + int('3') | int | Numeric text converted before addition | 8 |
Concatenation requires compatible string operands. Python does not automatically combine a string and a number with +.
Converting Text to Numeric Types
Conversion is needed when a value is text but your program must perform arithmetic. Type conversion changes a value from one type to another using functions such as int() and float().
Converting Whole-Number Text with int()
Use int() to convert text in a valid whole-number format to an integer.
x = int('5')
y = int('3')
print(x + y)
The result is 8. The conversion happens before the + operator performs arithmetic.
Converting Decimal Text with float()
A floating-point number is a decimal-capable numeric value represented by the float type. Use float() when the text represents a decimal value.
price = float('3.50')
quantity = 2
print(price * quantity)
The result is 7.0. The text passed to int() or float() must use a valid numeric format.
Common Beginner Errors
Unmatched or Incorrectly Nested Quotes
# Incorrect
message = 'It's ready'
The apostrophe in It's matches the opening single quote and ends the literal too early. Fix it by changing the outer delimiter or escaping the apostrophe:
message = "It's ready"
# or
message = 'It\'s ready'
Expecting String Addition to Be Numeric Addition
'5' + '3' produces '53' because both operands are strings. Convert them before arithmetic:
result = int('5') + int('3')
print(result) # 8
Adding a String and a Number
age = 20
# print('Age: ' + age) # TypeError
Python does not automatically combine a string and an integer. If the goal is text output, convert the number to text with str(). If the goal is arithmetic, convert valid numeric text with int() or float().
age = 20
print('Age: ' + str(age))
Invalid Input to int() or float()
# ValueError: letters are not a whole number
number = int('five')
int() raises ValueError when the source text is not valid whole-number text, such as text containing letters or an unsuitable decimal point. Check or clean the text first, and use float() when decimal input is intended.
Quick Reference
print(value)displays a string or computed result.type(value)reports whether a value is astr,int,float, or another type.int(text)converts valid whole-number text to an integer.float(text)converts valid numeric text to a floating-point number.+concatenates two strings or adds compatible numeric values.- Quoted digits such as
'5'are strings; unquoted digits such as5are integers.
Once you understand these foundations, continue with more Python string topics, such as indexing, slicing, methods, and formatted strings.