Skip to content

String literals in Python

  • by

In Python, a string literal is a sequence of characters enclosed within single quotes (”), double quotes (“”) or triple quotes (”’ ”’ or “”” “””). Strings are used to represent textual data and are immutable, meaning they cannot be modified after creation.

Using single quotes, double quotes, or triple quotes is interchangeable. The choice depends on the specific use case, and it can be convenient when the string contains one or the other type of quote within it.

For example:

single_in_double = "He said, 'Hello!'"
double_in_single = 'She said, "Hi!"'

Additionally, you can escape special characters using a backslash () in a string:

escaped_string = "This is an escaped newline: \nIt creates a new line."

Triple-quoted strings are often used for docstrings (documentation strings) in functions, classes, and modules, as they can span multiple lines and are used to provide information about the code.

def my_function():
    """This is a docstring.
    It provides information about the function."""
    pass

Note: In Python 3, strings are Unicode by default, which means they can handle characters from various languages and character sets without any issues.

String literals in Python example

Here are some examples of string literals in Python:

Single-quoted string:

single_quoted_string = 'Hello, I am a single-quoted string.'
print(single_quoted_string)

Double-quoted string:

double_quoted_string = "Hi, I am a double-quoted string."
print(double_quoted_string)

Triple-quoted multi-line string:

multi_line_string = '''This is a multi-line string.
It spans across multiple lines.
Triple quotes allow this flexibility.'''
print(multi_line_string)

Escaped characters:

escaped_string = "This is an escaped newline: \nIt creates a new line."
print(escaped_string)

Concatenating strings:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

Indexing and Slicing strings:

my_string = "Python"
print(my_string[0])      # Output: 'P'
print(my_string[-1])     # Output: 'n'
print(my_string[1:4])    # Output: 'yth'

String formatting:

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

Docstrings:

def my_function():
    """This is a docstring.
    It provides information about the function."""
    pass

print(my_function.__doc__)

Output:

String literals in Python

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *