1. Introduction
In Python, strings are not simply text to be displayed on the screen; they are also crucial data and parameters for many real-world problems, such as user input, data analysis, report generation, and application development.
Python's string manipulation capabilities are quite powerful, with many built-in functions that are easy to read, understand, and write.
This article will help you understand and master string manipulation in Python, from basic concepts to practical applications, through explanations and practical examples.

2. Ways to Create Strings in Python
2.1. Creating Standard String Literals
This is the simplest and most common way to declare text strings in Python. You can choose one of the following two methods:
- Single quotes
'...' - Double quotes
"..."
text1 = 'Hello AI VietNam'
text2 = "Hello AI VietNam"
Both commands create identical string variables. Why does Python provide two ways? Simply put, it makes Python code more readable and natural (closer to human language), and specifically reduces the need for the escape character \ when representing special characters.
The Principle:
- If the string contains single quotes
'→ use double quotes outside" - If the string contains double quotes
"→ use single quotes outside'
For example, with the sentence I'm learning Python: if only single quotes were allowed, we would have to write 'I\'m learning Python' (using the escape character \). However, because Python supports both, we can simply write: sentence = "I'm learning Python"
2.2. Creating Escape Sequences
In computing, not every character is recognizable text, digits, or symbols (A, B, 1, 2, @, #…). There are also control characters. These are used to:
- Start a new line
- Indent (tab)
- Signal the end of a line
- ...
These special characters do not have a clear visual shape. Therefore, when written in a string, Python (and many other languages) uses escape sequences—a symbol starting with a backslash \ to represent them.
In other words, escape sequences in Python are a way to represent control characters from the ASCII table (specifically those with values 0-31 and 127).
Common Escape Characters
| Character | Meaning |
|---|---|
\n |
New line |
\t |
Tab |
\" |
Double quote |
\' |
Single quote |
\\ |
Backslash |
Example code:
print("I love \nAI Vietnam")
The result will be displayed as:
I love
AI Vietnam
Escape sequences are particularly important when you want to:
- Print multiple lines of text
- Format reports
- Write text files
- System logs
If you do not want Python to process escape sequences, you can use raw strings, which are covered in the next section.
2.3. Creating Raw String Literals
A raw string is a string where Python preserves every character exactly as you typed it, just as it appears on the keyboard.
To create a raw string, simply add the prefix r immediately before the opening quote.
Example:
path = r"C:\new_folder\data\test.txt"
print(path)
# Output: 'C:\new_folder\data\test.txt'
If you used standard strings with escape sequences, you would have to write:
path = "C:\\new_folder\\test.txt".
As you can see, the standard version looks less natural, which is why raw strings are so useful.
Note: A raw string cannot end with a single backslash \.
If you write path = r"C:\temp\", it will cause an error because the system interprets the \" as an escaped quote. In this specific case, the workaround is: path = r"C:\temp\\" (adding an escape character before the backslash).
2.4. Creating Formatted String Literals (f-strings)
In practice, strings rarely stand alone; they are often combined with variable values, calculation results, or user input. For example, if you want to print Lan scored 9.5, where Lan and 9.5 are stored in variables name and score. Without formatted strings, you would write:
print(name + " scored " + str(score))
But with a formatted string (starting with f), you can simply write:
print(f"{name} scored {score}")
The syntax is much cleaner and eliminates the need for manual type conversion.
Additionally, Python allows you to insert expressions directly into f-strings without needing intermediate variables:
age = 20
print(f"Next year you will be {age + 1}")
# Output: 'Next year you will be 21'
Another powerful feature is calling methods directly inside the curly braces:
name = " python "
print(f"Name: {name.strip().title()}")
# Output: 'Name: Python'
f-strings are also used for number formatting, such as adding thousand separators or controlling decimal places for better readability:
money = 123456789
print(f"{money:,}")
# Output: 123,456,789
pi = 3.14159265
print(f"{pi:.2f}")
# Output: 3.14
2.5. Creating Strings Using the str() Function
In Python, the str() function acts as a string constructor.
Syntax str(object) which object can be any value or object. Since Python does not automatically convert other data types to strings during concatenation, you must use the str() function to convert variables or values into strings.
price = 50000
print("Product price: " + str(price) + " VND")
# Output: 'Product price: 50000 VND'
3. String Operators
In Python, strings are not only used to store text but can also be combined with several special operators. These operators allow us to concatenate strings, repeat strings, or check whether a substring exists within a larger string. This section explains how the most common operators work when dealing with string data types.
3.1. String Concatenation: The + Operator
The + operator is used to combine multiple strings into a single string. Each addition between strings creates a new string that contains the content of all the original strings. In this context, + is commonly referred to as the string concatenation operator.
city = "Ha Noi"
weather = "sunny"
sentence = "Today in " + city + " it is " + weather + "."
print(sentence)
# Output: 'Today in Ha Noi it is sunny.'
In the example above, the strings are concatenated from left to right. Python allows both strings stored in variables and string literals to be combined to produce the final result.
The shorthand concatenation operator +=
In addition to standard string concatenation, Python also supports the += operator as a more concise way to append strings.
url = "https://example.com"
url += "/login"
print(url)
# Output: 'Today in Ha Noi it is sunny.'
Although the syntax looks like the original string is being modified, Python actually creates a new string and reassigns it to the variable, since strings are immutable data types.
3.2.String Repetition: The * Operator
The * operator allows a string to be multiplied by an integer, creating a new string by repeating the original content multiple times.
Syntax:
string * n
n * string
Example:
print(3 * "Go ")
# Output: 'Go Go Go'
If the repetition count is 0 or a negative number, the result will be an empty string.
print("Hello" * 0) # Output: ''
print("Hello" * -2) # Output: ''
Applications of the * operator in data formatting
String repetition is often used to create separators, especially when displaying tabular data in the console.
For example, given the following data:
courses = [
["Python Basic", "120"],
["Data Analysis", "85"],
["Web Design", "60"],
]
We can create a function to display a formatted table:
def print_courses(data, headers):
max_width = max(len(header) for header in headers)
print(" | ".join(header.ljust(max_width) for header in headers))
print("-|-".join("-" * max_width for _ in headers))
for row in data:
print(" | ".join(item.ljust(max_width) for item in row))
Calling the function:
headers = ["Course Name", "Students"]
print_courses(courses, headers)
Output:
Course Name | Students
-------------|---------
Python Basic | 120
Data Analysis| 85
Web Design | 60
In this example, the * operator is used to repeat the - character, creating separators with a length that matches the column headers. As a result, the table appears cleaner, more balanced, and easier to read, even when the content length changes.
The shorthand repetition operator *=
Python also provides a shorthand form for string repetition using the *= operator.
Example:
border = "="
border *= 8
print(border)
# Output: '========'
3.3. Substring Checking: The in and not in Operators
The in and not in operators are used to determine whether a string appears within another string. The result of this check is a boolean value (True or False).
The in operator
The in operator checks whether the target string exists in the original string.
print("cat" in "The cat is sleeping") # True
print("dog" in "The cat is sleeping") # False
The not in operator
print("x" not in "apple") # True
print("a" not in "apple") # False
The not in operator returns True when the string does not appear in the given string, and returns False if it does appear.
4. Built-in functions for string processing
A built-in function is a core function provided by Python that can be used directly in Python programs without installing any external libraries. Built-in functions are particularly useful for simple, fast tasks.
For string processing, Python also provides many useful built-in functions. The following are the functions commonly used when working with strings:
| Function | Description |
|---|---|
len() |
Returns the length of the string being processed. |
str() and repr() |
Convert an object to a string. |
format() |
Formats a value as a string according to a format specification. |
ord() |
Converts a single character to its numeric code point. |
chr() |
Converts an integer code point to the corresponding character. |
To make the functions listed above clearer, the following sections introduce each of them in more detail and show how to use them in real string-processing tasks.
4.1. Counting elements: len()
To start exploring len(), consider the example below:
password1 = 'iloveai'
password2 = 'AIVietNam'
def check_password(password):
if len(password) < 8 or len(password) > 25:
print('Password for registration is invalid')
else:
print('Registration successful')
check_password(password1)
# Output: 'Password for registration is invalid'
check_password(password2)
# Output: 'Registration successful'
This is a simplified version of a password-validity check commonly used in social-network signups, where validity is determined by the number of characters.
From the example, it is clear that determining the number of characters in a string is a frequent operation, and the len() function is a very useful tool for that purpose.
When you pass a string to len(), it returns the number of characters in that string. Some simple examples:
len('AIOConquer') # Output: 10
len('') # Output: 0
Because the string 'AIOConquer' contains 10 characters, len() returns 10. Note that when you pass an empty string to len(), it will return 0.
Besides strings, the built-in function len() can also be used with other data types such as lists, tuples, and dictionary.
4.2. Converting objects to strings: str() and repr()
When using string-processing functions, we often need to ensure the data we are working with is a string. In practice, data commonly appears in many types other than string. To convert other types to string representations, Python provides two built-in functions: str() and repr().
Starting with str(): when you pass an object to str(), it returns a human-friendly string representation. Examples:
str(26) # Output: '26'
str([1, 2, 3]) # Output: '[1, 2 ,3]'
str({"one": 1, "two": 2, "three": 3})
# Output: '{"one": 1, "two": 2, "three": 3}'
repr() returns a string representation intended to be unambiguous and more useful for developers. Examples:
repr(26) # Output: '26'
repr([1, 2, 3]) # Output: '[1, 2 ,3]'
repr({"one": 1, "two": 2, "three": 3})
# Output: '{"one": 1, "two": 2, "three": 3}'
From the examples above, str() and repr() produce similar results for many built-in Python types.
To distinguish the two, consider these examples:
a = 'AIO'
str(a) # Output: 'AIO'
repr(a) # Output: "'AIO'"
import numpy as np
a = np.array([1, 2, 3])
str(a) # Output: '[1, 2 ,3]'
repr(a) # Output: 'array([1, 2 ,3])'
In the NumPy example, repr() returns more complete information about how the object is constructed (which can help a developer reconstruct the object), while str() returns a more concise, user-friendly representation.
4.3. Formatting strings: format()
The built-in format() function converts an input value into a string formatted according to a format specifier. Examples and commonly used format specifiers:
format(3.14159 , ".4f")
# Output: '3.1416'
format(10, ".2f")
# Output: '10.00'
format(1234567, ",")
# Output: '1,234,567'
format(0.25, ".1%")
# Output: '25.0%'
format(10, "b")
# Output: '1010'
In the examples above, the specifiers ".4f" and ".2f" format the input as floating-point numbers rounded to 4 and 2 decimal places respectively.
The specifier "," inserts commas as thousand separators. The specifier ".1%" formats the value as a percentage. The "b" specifier formats an integer in binary.
4.4. Character code points: ord() and chr()
Computers do not directly understand the characters humans use; they store and process information as numbers. To represent characters in a computer, each character is assigned a unique number, commonly called a code point.
The widely used encoding standards that map characters to code points include ASCII and Unicode. The ASCII table primarily contains basic Latin characters commonly used in English. However, many characters used worldwide are outside ASCII; Unicode defines the code points for the majority of characters used in digital content.
The built-in function ord() returns the code point (an integer) for a single character. Note that characters within the ASCII range will return their ASCII code points; other characters return their Unicode code points. Examples:
ord("A")
# Output: 65
ord("π")
# Output: 960
ord("∞")
# Output: 8734
ord("😀")
# Output: 128512
Conversely, chr() converts a numeric code point back to the corresponding character:
chr(65)
# Output: 'A'
chr(960)
# Output: 'π'
chr(8734)
# Output: '∞'
chr(128512)
# Output: '😀'
5. Indexing and Slicing Strings
Indexing and slicing define how Python allows you to observe and extract data from strings. They are foundational not because they are syntactically complex, but because they encode Python’s core design choices around sequence semantics, immutability, and error handling. Understanding the underlying rules allows you to reason correctly about string behavior, avoid boundary errors, and write code that is both safe and idiomatic.
5.1. Indexing Strings
Definition and Rule Overview
Indexing is the operation of retrieving a single character from a string using an integer position. A Python string is an ordered, immutable sequence of characters, and indexing selects exactly one element from that sequence.
s = "Python"
s[0] # 'P'
Indexing is a strict access operation: it either succeeds with a valid character or fails immediately with an error.
Zero-Based Indexing
Python uses zero-based indexing, meaning the first character is located at index 0.
s = "Python"
s[0] # 'P'
s[1] # 'y'
s[2] # 't'
s[3] # 'h'
s[4] # 'o'
s[5] # 'n'
Conceptually, an index represents an offset from the start of the sequence, not a human-oriented position number. This model is consistent across all Python sequence types and enables uniform boundary reasoning.
Positive vs. Negative Indexing (Internal Resolution)
In addition to non-negative indices, Python supports negative indices, which count from the end of the string.
s = "Python"
s[-1] # 'n'
Internally, Python resolves a negative index using the rule:
effective_index = len(s) + index
For example:
len("Python") # 6
"Python"[-1] -> 6 + (-1) = 5
After being resolved in this way, Python applies the same bounds checking mechanism as it does for non-negative indices.
Therefore, negative indexing is not a special case in the indexing process - it is simply an alternative notation for referring to positions counted from the end of the string.
Error Behavior and Strictness
Indexing enforces strict boundary rules:
- The index must be an integer
- The resolved index must satisfy
0 ≤ index < len(s) - Otherwise, Python raises
IndexError
Python does not clamp indices or return sentinel values. Invalid access is treated as a programming error, and failure is explicit by design.
s = "Python"
s[6] # IndexError
s[-7] # IndexError
Immutability Implications
Strings in Python are immutable. Indexing allows you to access a character, but not to modify it.
s = "Python"
s[0] = "y" # TypeError
This reflects a critical conceptual distinction:
- Accessing data: reading an existing value (allowed)
- Modifying data: changing the underlying object (disallowed)
Indexing always returns a new string object of length 1, never a mutable view into the original string.
Best Practices
- Use negative indices when reasoning from the end of a string
- Validate length when indexing external or user-controlled input
- Keep index expressions simple and intention-revealing
- Use indexing only when exactly one character is required
5.2. Slicing Strings
Definition and Purpose
Slicing extracts a subsequence of characters from a string. Unlike indexing, slicing operates on ranges and may return zero, one, or many characters.
s = "Python"
s[1:4] # 'yth'
Slicing always returns a new string and never mutates the original.
Syntax and Parameters:
The full slicing form is:
s[start:stop:step]
start: index where slicing begins (inclusive)stop: index where slicing ends (exclusive)step: stride between elements (defaults to1)
Each component is optional, but each has fixed semantic rules.
Inclusive vs. Exclusive Boundaries
Slicing follows a deliberate boundary convention:
startis inclusivestopis exclusive
s = "Python"
s[0:2] # 'Py'
This rule ensures a predictable invariant:
len(s[start:stop]) == stop - start
The exclusivity of stop is not arbitrary - it simplifies composition, avoids overlap, and makes adjacent slices align cleanly.
Slice Normalization Rules
Before slicing is executed, Python normalizes slice bounds:
- Missing values are replaced with defaults
| Case | Default value |
|---|---|
start omitted |
0 |
stop omitted |
len(s) |
- Out-of-range indices are clamped to valid limits
s = "Python"
s[:100] # 'Python'
s[-100:3] # 'Pyt'
Because of this normalization process, slicing never raises IndexError. An invalid or empty range simply produces an empty string.
Common Slicing Patterns
s = "Python"
s[:3] # from start: 'Pyt'
s[3:] # to end: 'hon'
s[:] # full copy: 'Python'
These forms are preferred when intent matters more than explicit numeric bounds.
Negative Indices and Reverse Slicing
Negative indices in slicing behave exactly the same way as in single - character indexing:
s = "Python"
s[-3:] # 'hon'
s[:-3] # 'Pyt'
They allow you to reason naturally from the end of the string, without having to manually compute the string’s length.
Step and Reverse Traversal
The step parameter controls traversal direction and spacing.
s = "Python"
s[::2] # 'Pto'
A negative step reverses traversal order:
s[::-1] # 'nohtyP'
Mechanistically:
- Traversal starts at the end of the string
- Each step moves backward by one position
- Characters are accumulated in reverse order
This is why [::-1] correctly and idiomatically reverses a string.
Best Practices
- Use slicing for ranges, indexing for single characters
- Prefer omitted bounds (
[:],[:n],[n:]) for readability - Rely on slice normalization instead of manual checks
- Use
stepintentionally; avoid obscuring intent
6. Interpolate and format strings
6.1. % operator
Prior to Python 3.6, the % (modulo) operator and the .format() method were the two main tools used to interpolate values, variables, and expressions within strings. In this section, we will explore how to use the % operator.
Below is code that uses the modulo operator to interpolate a string:
vietnam = "Vietnam"
"Hello AI %s" % vietnam
# Output: 'Hello AI Vietnam'
It can be seen that the modulo operator takes two operands:
- The left operand is a string containing one or more conversion specifiers (in the example above, the string
%s) - The right operand is the object interpolated into the left string
In the example above, the value of the variable vietnam is interpolated into the conversion specifier %s. The string %s consists of two components, (1) % is the character identifying this as a conversion specifier and (2) s is the format of the object after interpolation. Specifically, the character s stands for string, meaning that the object to be replaced in this conversion specifier must be in string form.
To better understand conversion specifiers, consider the following code:
number = 123.456
"%s is a string" % number
# Output: '123.456 is a string'
"%d is a decimal" % number
# Output: '123 is a decimal'
"%f is a float" % number
# Output: '123.456000 is a float'
"%.2f is a float" % number
# Output: '123.46 is a float'
As you can see, even with the same variable number, changing the format changes the interpolated value.
d(decimal) is the decimal format, forcing the value to decimal.f(float) forces the value to a floating-point number with 6 decimal places.- Adding
.2beforefchanges the object's format to a floating-point number rounded to 2 decimal places.
To interpolate multiple values simultaneously, we replace the right-hand operand variable with a tuple. The interpolation order will match the order of each element in the tuple.
hello = "Hello"
vietnam = "Vietnam"
"%s AI %s" % (hello, vietnam)
# Output: 'Hello AI Vietnam'
Besides tuples, we can also use dictionary data structures. For dictionary data types, the interpolation operator is defined by adding a key after the % character and the format of the conversion specification.
hello = "Hello"
vietnam = "Vietnam"
"%(hello)s AI %(vietnam)s" % {"vietnam": vietnam, "hello": hello}
# Output: 'Hello AI Vietnam'
Although the % operator allows for simple and quick interpolation, it also has some limitations. For example, if we want to interpolate a tuple rather than individual elements within it, we must enclose that tuple within another tuple.
ai = "AI"
vietnam = "Vietnam"
"Hello %s" % (ai, vietnam)
# TypeError: not all arguments converted during string formatting
"Hello %s" % ((ai, vietnam),)
# Output: 'Hello ('AI', 'Vietnam')'
6.2. .format() method
The .format() method is an improved version of the % operator, addressing several issues and supporting string formatting mini-language. .format() uses curly braces instead of conversion statements.
hello = "Hello"
vietnam = "Vietnam"
"{} AI {}".format(hello, vietnam)
# Output: 'Hello AI Vietnam'
By default, the interpolation order matches the order of the arguments of the .format() method. However, we can customize the interpolation order by adding indices within the curly braces.
hello = "Hello"
vietnam = "Vietnam"
"{1} AI {0}".format(hello, vietnam)
# Output: 'Vietnam AI Hello'
In addition to indexes, we can also use keyword arguments to determine the interpolation order.
"{vietnam} AI {hello}".format(hello="Hello", vietnam="Vietnam")
# Output: 'Vietnam AI Hello'
You can also pass elements of a dictionary into .format using two asterisks **.
dic = {hello="Hello", vietnam="Vietnam"}
"{vietnam} AI {hello}".format(**dic)
# Output: 'Vietnam AI Hello'
Because .format() does not use conversion specifiers to format interpolated objects, .format() uses format specifiers. Similar to the syntax of conversion specifiers, the syntax of format specifiers simply replaces the % character with :.
number = 123.456
"{:.2f} is a float".format(number)
# Output: '123.46 is a float'
one = 1
two = 2
three = 3
"{2:d} + {1:d} = {0:d}".format(three, two, one)
# Output: '1 + 2 = 3'
In the code above, the 2 in 2:d is the index of the one argument, while :d is the decimal format.
6.3. F-String
After Python version 3.6, f-string provided users with another way to interpolate strings. The syntax of f-string is similar to .format() but more concise. Simply add a lowercase or uppercase f before the string and enclose values, variables, objects, and expressions in curly braces for interpolation.
hello = "Hello"
vietnam = "Vietnam"
f"{hello} AI {vietnam}"
# Output: 'Hello AI Vietnam'
You can also interpolate most expressions in Python using f-strings. Below is an example code showing how f-strings can interpolate computational expressions, methods, and even list comprehensions:
f"1 + 2 = {1 + 2}"
# Output: '1 + 2 = 3'
hello = "Hello"
vietnam = "Vietnam"
f"{hello} AI {vietnam.upper()}"
# Output: 'Hello AI VIETNAM'
f"{[2**n for n in range(1, 5)]}"
# Output: '[2, 4, 8, 16]'
Similar to .format(), f-string also uses the format specifier to format the interpolated string.
number = 123.456
f"{number:.2f} is a float"
# Output: '123.46 is a float'
Besides the usual interpolation, f-strings also have a very useful feature that makes debugging easier for programmers. For example, if we want to quickly check the value of a variable, we use the syntax:
number = 123.456
print(f"{number = }")
# Output: number = 123.456
number = 123.456
print(f"{number= }")
# Output: number= 123.456
number = 123.456
print(f"{number=}")
# Output: number=123.456
For Python versions 3.12 and later, f-strings have undergone some upgrades.
In Python versions 3.11 and earlier, using single quotes ' within a string required wrapping the string with double quotes ", and vice versa. Otherwise, Python would throw an error. However, in versions after 3.12, you can use any type of quotation mark without any restrictions.
# Python 3.11
dic = {"hello": "Hello", "vietnam": "Vietnam"}
f"{dic['hello']} AI {dic['vietnam']}"
# Output: 'Hello AI Vietnam'
f"{dic["hello"]} AI {dic["vietnam"]}"
# SyntaxError: f-string: unmatched '['
# Python 3.12
f"{dic["hello"]} AI {dic["vietnam"]}"
# Output: 'Hello AI Vietnam'
Another drawback of f-strings in Python 3.11 and earlier was the inability to use backslashes (`\") in f-string expressions. Python 3.12 fixed this:
# Python 3.11
words = ["Hello", "AI", "Vietnam"]
f"{'\n'.join(words)}"
# SyntaxError: f-string expression part cannot include a backslash
# Python 3.12
f"{'\n'.join(words)}"
# Output: 'Hello\nAI\nVietnam'
F-String now also allows you to write inline comments within interpolation expressions.
# Python 3.12
vietnam = "Vietnam"
f"""Hello AI {
vietnam # This is a inline comment
}"""
# Output: 'Hello AI Vietnam'
Additionally, the error message for f-string version 3.12 is more detailed. When you enter this code:
f"{42 + }"
Versions below 3.12 will show the following error:
File "<stdin>", line 1
(42 + )
^
SyntaxError: f-string: invalid syntax
As for versions 3.12 and later:
File "<stdin>", line 1
f"{42 + }"
^
SyntaxError: f-string: expecting '=', or '!', or ':', or '}'
6.4. Compare % operator, .format() method and f-string
In terms of performance, f-strings run faster than the % operator and the format() method. Besides that, f-strings also have many useful features as discussed in the sections above. However, there are cases where % and format() would be more appropriate choices.
Dictionary interpolation is one such case. The syntax of f-strings in this case would look more cumbersome than using .format().
dic = {"hello": "Hello", "vietnam": "Vietnam"}
# f-string
f"{dic['hello']} AI {dic['vietnam']}"
# Output: 'Hello AI Vietnam'
# .format()
"{hello} AI {vietnam}".format(**dic)
# Output: 'Hello AI Vietnam'
Another example is lazy evaluation.
F-String or .format() performs string interpolation immediately upon declaration; this is called eager evaluation. Interpolation using the % operator only occurs when using the % operator, not when declaring the string; this is called lazy evaluation. To understand this better, let's look at the following example:
vietnam = 'Vietnam'
# f-string
a = f"Hello AI {vietnam}" # Ngay tại thời điểm này a = 'Hello AI Vietnam'
# .format()
b = "Hello AI {}".format(vietnam) # Ngay tại thời điểm này b = 'Hello AI Vietnam'
# %
c = "Hello AI %s" # Ngay tại thời điểm này c = 'Hello AI %s'
c = c % vietnam # Ngay tại thời điểm này c = 'Hello AI Vietnam'
As you can see, if we don't want to interpolate when declaring a string, we use the method of declaring a string with a conversion specified. We only use the modulo operator when we actually need interpolation. This is useful when not every string in the program needs interpolation.
The logging module allows programmers to divide messages into levels (e.g., debug level, warning level, etc.). Depending on the needs, programmers can configure which level of messages to receive. This helps the program only calculate the necessary messages, optimizing program performance.
Suppose a program has hundreds of debug-level messages and ten warning-level messages. The programmer is currently only interested in the warning messages. If we use f-strings or .format() to define the messages, all messages are interpolated, which is unnecessarily costly. If we use %, only the messages of the correct level will be interpolated.
import logging
msg = "This is a %s message!"
logging.warning(msg, "WARNING")
# Output: WARNING:root:This is a WARNING message!
logging.debug(msg, "DEBUGGING")
# Hàm này vì không đúng cấp nên không thực hiện nội suy
7. Conclusion
And that's Python's diverse tools for initializing and manipulating strings using built-in operators and functions. The blog post also guides you through extracting elements or parts of an existing string using indexing and slicing operators. It also introduces and compares string interpolation methods.
8. References
Jablonski, J. (2024, November 30). Python's F-String for String Interpolation and Formatting. Real Python. https://realpython.com/python-f-strings
Ramos, L.P. (2024, December 22). Strings and Character Data in Python. Real Python. https://realpython.com/python-strings
Chưa có bình luận nào. Hãy là người đầu tiên!