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:

Python
>>> 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

Python Syntax
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:

Python
>>> empty_string = ""
>>> empty_string
''

Creating single-line strings using a literal with single and double quotes:

Python
>>> 'This is a string within single quotes.'
>>> "This is a string within double quotes."

Creating a multi-line string using triple quotes:

Python
>>> """This is a
...    multi-line string."""

Accessing characters by index:

Python
>>> greeting = "Hello!"
>>> greeting[0]
'H'
>>> greeting[2]
'l'
>>> greeting[-1]
'!'

Creating strings with f-strings

Python
>>> f"The number is {42}"
'The number is 42'

Craating raw strings:

Python
>>> 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:

Python
>>> 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.

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!

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 6, 2024 • Reviewed by Dan Bader