Home > Backend Development > Python Tutorial > What Does the Single Underscore '_' Mean in Python?

What Does the Single Underscore '_' Mean in Python?

DDD
Release: 2024-12-27 11:13:16
Original
918 people have browsed it

What Does the Single Underscore

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 "_"

  1. Result Placeholder in Interactive Interpreter:

    • "_" stores the result of the last executed expression in an interactive Python session, providing easy access to the previous output.
  2. Translation Lookup:

    • "_" indicates a placeholder for translation during internationalization (i18n) processes. It is used to retrieve translated strings, ensuring proper language localization.
  3. "Throwaway" Variable:

    • "-" serves as a placeholder to deliberately discard a section of a function's result or unused parameters in a signature. This practice helps keep code concise and avoids unnecessary variable assignment.

Example:

Discarding a Variable

label, has_label, _ = text.partition(':')
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template