Meaning of the Single Underscore Variable in Python
In Python, the single underscore symbol ("_") plays a special role in specific contexts, carrying conventional meanings for different purposes.
Conventional Uses of "_"
Result Placeholder in Interactive Interpreter:
Translation Lookup:
"Throwaway" Variable:
Example:
Discarding a Variable
label, has_label, _ = text.partition(':')
Here, "_" is used to ignore the third return value from the text.partition() function, which is the index of the separator character.
Unused Function Parameter
def callback(_): return True
In this example, the lambda function callback takes one parameter, "_," but does not use it, as indicated by the single underscore.
Note: The third usage of "_" as a "throwaway" variable can conflict with its use for translation lookup. Therefore, a double underscore ("__") is commonly used as an alternative "throwaway" variable in scenarios that involve translation.
Linters often recognize the use of "_" as a "throwaway" variable and raise warnings if the variable is unused. Additionally, in pattern matching statements introduced in Python 3.10, "_" serves as a wildcard pattern, indicating that the runtime should ignore the value associated with that variable.
The above is the detailed content of What Does the Single Underscore '_' Mean in Python?. For more information, please follow other related articles on the PHP Chinese website!