Python Variable Usage, Naming Conventions, and Common Operations
This article teaches Python developers how to write cleaner, more elegant code by mastering variable unpacking, underscore placeholders, type annotations, PEP 8 naming rules, numeric literals, floating‑point precision handling with Decimal, boolean arithmetic tricks, and a wide range of string manipulation techniques, all illustrated with practical code examples.
When reading others' source code you may feel it looks sophisticated, but your own code can feel cheap; improving code quality requires mastering advanced usage beyond basic knowledge.
Variable unpacking allows assigning multiple values from an iterable in a single statement:
usernames = ['honey', 'jack']
author, reader = usernamesNested structures can be unpacked with parentheses:
usernames = [["honey", 90], ["jack", 100]]
(author, author_score), (reader, reader_score) = usernamesDynamic unpacking uses the asterisk to capture remaining items as a list:
usernames = ['honey', 90, 100, 'jack']
author, *score, reader = usernames
print(score) # [90, 100]The single underscore _ serves as a throw‑away placeholder in assignments:
usernames = ['honey', 90, 100, 'jack']
author, *_, _ = usernamesType annotations (Python 3.5+) let you declare variable types, though they are only hints and need external tools like mypy for checking:
from typing import List
def remove_invalid(items: List[int]):
"""Remove invalid elements"""
...PEP 8 naming conventions recommend:
snake_case for regular variables (e.g., max_value)
UPPER_CASE_WITH_UNDERSCORES for constants (e.g., MAX_VALUE)
leading underscore for internal‑use variables (e.g., _local_var)
trailing underscore when a name clashes with a keyword (e.g., class_)
Other PEP 8 rules cover class names (CamelCase) and function names (snake_case).
Small tricks :
Boolean values behave as integers (True = 1, False = 0), enabling concise counting:
numbers = [1, 2, 3, 4, 5, 6, 7]
count = sum(i % 2 == 0 for i in numbers) # counts even numbersNumeric literals can include underscores for readability: i = 1_000_000 Floating‑point arithmetic may produce unexpected results; use decimal.Decimal for exact decimal math:
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2')) # 0.3Passing a float directly to Decimal defeats the purpose because the float is already imprecise:
print(Decimal(0.1)) # shows the binary representation errorString operations include iteration, slicing, reversing, and built‑in methods:
s = "hello, python!"
for c in s:
print(c)
# reverse using slicing
print(s[::-1])
# reverse using reversed()
print(''.join(reversed(s)))Formatting options:
C‑style 'hello %s' % name (discouraged) str.format() – supports positional arguments
f‑strings (Python 3.6+)
name = 'python'
print(f'Hello, {name}')
print('{0}: name={0} score={1}'.format('jack', 100))String concatenation can be done with join or the += operator:
output = ['hello', 'python']
print(' '.join(s for s in output))Splitting and partitioning differ: split() returns a list, partition() returns a 3‑tuple (before, sep, after):
output = "name:jack"
print(output.split(':')) # ['name', 'jack']
print(output.partition(':')) # ('name', ':', 'jack')Replacing characters:
s = 'hello, python.'
print(s.replace(',', '!')) # hello! python.
# translate for multiple replacements
table = s.maketrans(',.', '!。')
print(s.translate(table)) # hello! python。Strings vs. bytes :
Unicode str can be encoded to bytes via
.encode() bytescan be decoded back to str via
.decode() s = 'hello, python.'
byte_s = s.encode('UTF-8')
print(byte_s) # b'hello, python.'
byte_object = b'hello'
print(type(byte_object)) # <class 'bytes'>
print(byte_object.decode()) # helloWhen writing to files, specify an encoding (e.g., encoding='UTF-8') so Python automatically converts strings to bytes:
with open('output.txt', 'w', encoding='UTF-8') as fp:
fp.write("hello python")If no encoding is given, Python falls back to the system’s preferred encoding (often UTF‑8 on macOS):
import locale
print(locale.getpreferredencoding()) # UTF-8Practicing these techniques will gradually lead to more elegant Python code and help you become a Python master.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
