SoFunction
Updated on 2025-03-03

Detailed explanation of string modifiers in Python

1. Raw String -rorR

userorRPrefix, which tells Python that all backslashes in a string are normal characters, not escape characters. This is very useful when dealing with file paths, regular expressions, etc.

path = r'C:\new_folder\'  # Original string

2. Formatted String -forF

useforFPrefix, you can embed expressions in strings. These expressions are evaluated at runtime and the result is inserted into the string. This string is called f-string and was introduced in Python 3.6.

name = "Alice"
age = 30
message = f'{name} is {age} years old.'  # Format string

3. Unicode string -uorU

In Python 3, all strings are Unicode by default, souPrefixes are usually no longer needed. However, in Python 2, it is used to create Unicode strings.

# In Python 3:text = u'Hello, world!'  # Unicode string# In Python 2:text = u'Hello, world!'  # Unicode String

4. Byte String (Byte String) -borB

useborBPrefix to create a byte string, not a text string. Byte strings are used to process binary data and are often used for file I/O and network transmission.

data = b'Hello, world!'  # Byte string

5. Triple Quotes

Triple quotes can be used to define strings that span multiple lines. This string can be used in triple single quotes (''') or triple double quotes (""") Definition.

multiline_str = """This is a
multiline string that spans
multiple lines."""

6. Combination of modifiers

String modifiers can be used in combination. For example, both the original string should be used and the formatting should be done:

path = r'C:\new_folder\'
name = "Alice"
message = fr'{name}\'s file is located at {path}'
print(message)
# Output: Alice's file is located at C:\new_folder\

Sample code

# Use original stringraw_path = r'C:\Users\Example\Documents\'
print(raw_path)
# Use format stringsname = "John"
age = 28
greeting = f'Hello, {name}. You are {age} years old.'
print(greeting)
# Use Unicode stringsunicode_str = u'The world of 'こんにちはone'  # This is Unicode by default in Python 3print(unicode_str)
# Use byte stringsbyte_str = b'This is a byte string'
print(byte_str)
# Use multi-line stringsmultiline_str = """This is a string
that spans multiple
lines."""
print(multiline_str)
# Use raw and formatted strings in combinationfile_path = r'C:\Users\Example\Documents'
filename = ""
full_path = fr'{file_path}\{filename}'
print(full_path)

This is the end of this article about string modifiers in Python. For more related Python string modifier content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!