str
The built-in str
data type represents sequences of characters and is used to manipulate textual data. Python strings are immutable sequences, meaning once defined, they can’t be changed. Here’s how you can create a strings:
>>> greeting = "Hello, World!"
>>> greeting
'Hello, World!'
str
Literals
In Python, there are several types of string literals, each with a different syntax and purpose:
Literal Type | Syntax | Description |
---|---|---|
Single-quoted | 'text' |
Basic string literal using single quotes. Allows newlines with \n . |
Double-quoted | "text" |
Basic string literal using double quotes. Similar to single-quoted strings. |
Triple-quoted | '''text''' or """text""" |
Multiline string literal. It reserves newlines and whitespace formatting. |
Raw strings | r"text" or r'text' |
Raw string where backslashes are treated literally. Commonly used in regex. |
Formatted string or f-strings | f"text {variable}" |
Allows embedded expressions with {} ; evaluated at runtime. Introduced in Python 3.6. |
str
Constructor
str(object="")
str(object=b"", encoding="utf-8", errors="strict")
Arguments
Argument | Description | Default Value |
---|---|---|
object |
An object to convert into a string. | "" |
encoding |
The encoding to use for bytes-like objects. | "utf-8" |
errors |
The error handling scheme for encoding errors. | "strict" |
Return Value
- Returns a Python
str
object
str
Examples
Creating an empty string:
>>> empty_string = ""
>>> empty_string
''
Creating single-line strings using a literal with single and double quotes:
>>> 'This is a string within single quotes.'
>>> "This is a string within double quotes."
Creating a multi-line string using triple quotes:
>>> """This is a
... multi-line string."""
Accessing characters by index:
>>> greeting = "Hello!"
>>> greeting[0]
'H'
>>> greeting[2]
'l'
>>> greeting[-1]
'!'
Creating strings with f-strings
>>> f"The number is {42}"
'The number is 42'
Craating raw strings:
>>> r"Hello\nWorld"
'Hello\\nWorld'
str
Methods
Method | Description |
---|---|
.capitalize() |
Returns a copy with the first character capitalized. |
.casefold() |
Returns a casefolded copy for case-insensitive comparisons. |
.center() |
Centers the string, padding with spaces. |
.count() |
Returns the number of non-overlapping occurrences of a substring. |
.encode() |
Encodes the string using the specified encoding. |
.endswith() |
Checks if the string ends with a specified suffix. |
.expandtabs() |
Expands tabs in the string to multiple spaces. |
.find() |
Finds the first occurrence of a substring. |
.format() |
Formats the string using positional and keyword arguments. |
.format_map() |
Formats the string using a dictionary. |
.index() |
Finds the first occurrence of a substring, raises an error if not found. |
.isalnum() |
Checks if all characters are alphanumeric. |
.isalpha() |
Checks if all characters are alphabetic. |
.isascii() |
Checks if all characters are ASCII characters. |
.isdecimal() |
Checks if all characters are decimal characters. |
.isdigit() |
Checks if all characters are digits. |
.isidentifier() |
Checks if the string is a valid identifier. |
.islower() |
Checks if all characters are lowercase. |
.isnumeric() |
Checks if all characters are numeric. |
.isprintable() |
Checks if all characters are printable. |
.isspace() |
Checks if all characters are whitespace. |
.istitle() |
Checks if the string is title-cased. |
.isupper() |
Checks if all characters are uppercase. |
.join() |
Concatenates an iterable of strings with the string as the separator. |
.ljust() |
Left-aligns the string, padding with spaces. |
.lower() |
Converts the string to lowercase. |
.lstrip() |
Removes leading whitespace characters. |
.maketrans() |
Returns a translation table for replacements. |
.partition() |
Splits the string at the first occurrence of a substring. |
.replace() |
Replaces occurrences of a substring with another substring. |
.rfind() |
Finds the last occurrence of a substring. |
.rindex() |
Finds the last occurrence of a substring, raises an error if not found. |
.rjust() |
Right-aligns the string, padding with spaces. |
.rpartition() |
Splits the string at the last occurrence of a substring. |
.rsplit() |
Splits the string into a list by a separator. |
.rstrip() |
Removes trailing whitespace characters. |
.split() |
Splits the string into a list by whitespace or a separator. |
.splitlines() |
Splits the string at line breaks. |
.startswith() |
Checks if the string starts with a specified prefix. |
.strip() |
Removes leading and trailing whitespace characters. |
.swapcase() |
Swaps lowercase characters to uppercase and vice versa. |
.title() |
Converts the string to title case. |
.translate() |
Translates characters in the string based on a translation table. |
.upper() |
Converts the string to uppercase. |
.zfill() |
Pads the string with zeros on the left until it reaches a specified length. |
str
Common Use Cases
The most common use cases for the str
include:
- Storing and displaying textual data
- Formatting text output
- Parsing and processing user input
- Creating and handling text-based protocols
str
Real-World Example
Suppose you need to generate a formatted report from user input data. Strings are ideal for building such output, using methods to capitalize, format, and concatenate the input:
>>> name = "john doe"
>>> balance = 1500.75
>>> report = f"Account holder: {name.title()}\nBalance: ${balance:,.2f}"
>>> print(report)
Account holder: John Doe
Balance: $1,500.75
In this example, strings are used to format and present user data in a readable format.
Related Resources
Tutorial
Strings and Character Data in Python
In this tutorial, you'll learn how to use Python's rich set of operators and functions for working with strings. You'll cover the basics of creating strings using literals and the str() function, applying string methods, using operators and built-in functions with strings, and more!
For additional information on related topics, take a look at the following resources:
- A Guide to Modern Python String Formatting Tools (Tutorial)
- Python String Formatting: Available Tools and Their Features (Tutorial)
- How to Format Floats Within F-Strings in Python (Tutorial)
- Python's Format Mini-Language for Tidy Strings (Tutorial)
- Efficient String Concatenation in Python (Tutorial)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)
- Formatting Python Strings (Course)
- A Guide to Modern Python String Formatting Tools (Quiz)
- Python String Formatting Tips & Best Practices (Course)
- Python String Formatting: Available Tools and Their Features (Quiz)
- Formatting Floats Inside Python F-Strings (Course)
- Format Floats Within F-Strings (Quiz)