Python编程tips

pydantic BaseModel 与dict的相互转换

如果属性名相同

dict -> BaseModel

class MyClass(BaseModel)
    attr1: Optional[str]
    attr2: Optional[str]
my_dict={"attr1":"abc", "attr2":"xyz"}
myclass = MyClass(**my_dict)

BaseModel -> dict:

my_dict = my_class.model_dump()



1. 切片(Slicing)

In Python, slicing is a way to extract a portion of a sequence (like a list, string, or tuple) using a specific range of indices. The syntax is:

sequence[start:stop:step]
  • start: The index where the slice begins (inclusive). If omitted, defaults to the beginning (0).
  • stop: The index where the slice ends (exclusive). If omitted, defaults to the end of the sequence.
  • step: The increment between indices. If omitted, defaults to 1. A negative step reverses the direction.

Slicing a List

my_list = [0, 1, 2, 3, 4, 5]

# Basic slice: get elements from index 1 to 3 (exclusive)
print(my_list[1:4])  # Output: [1, 2, 3]

# Omitting start: starts from index 0
print(my_list[:3])  # Output: [0, 1, 2]

# Omitting stop: goes until the end
print(my_list[2:])  # Output: [2, 3, 4, 5]

# Using step: get every second element
print(my_list[::2])  # Output: [0, 2, 4]

# Negative step: reverse the list
print(my_list[::-1])  # Output: [5, 4, 3, 2, 1, 0]

Slicing a String

text = "Hello, World!"

# Get substring from index 0 to 5
print(text[0:5])  # Output: Hello

# Get every second character
print(text[::2])  # Output: Hlo ol!

# Reverse the string
print(text[::-1])  # Output: !dlroW ,olleH

Slicing a Tuple

my_tuple = (10, 20, 30, 40, 50)

# Get elements from index 1 to 3
print(my_tuple[1:3])  # Output: (20, 30)

# Reverse the tuple
print(my_tuple[::-1])  # Output: (50, 40, 30, 20, 10)

Key Points

  • Negative Indices: You can use negative indices to count from the end of the sequence (e.g., -1 is the last element).
  print(my_list[-3:])  # Output: [3, 4, 5]
  • Out-of-Bounds: Python handles out-of-bounds indices gracefully, returning as much of the sequence as possible.
  print(my_list[2:10])  # Output: [2, 3, 4, 5]
  • Immutable Sequences: For immutable types like strings and tuples, slicing creates a new object.
  • Step of 0: A step of 0 is invalid and raises a ValueError.

Practical Use Cases

  • Extracting substrings or sublists.
  • Reversing sequences ([::-1]).
  • Skipping elements with a step value.
  • Processing data in chunks.

2. 补齐(padding)

In Python, you can pad an integer to a fixed-length string using several methods. Here are the most common approaches:

1. Using zfill()

The zfill() method pads a string with zeros on the left to reach the specified length. It works on a string representation of the integer.

number = 42
padded = str(number).zfill(5)  # Pad to 5 digits
print(padded)  # Output: 00042
  • Note: If the number has fewer digits than the specified length, it adds leading zeros. If the number has more digits, it returns the original string unchanged.

2. Using f-string with width specification

You can use an f-string with a width specifier to pad with zeros.

number = 42
padded = f"{number:05d}"  # Pad to 5 digits
print(padded)  # Output: 00042
  • The 05d format means: use decimal (d), pad with zeros to a width of 5.

3. Using str.format()

Similar to f-strings, you can use the str.format() method.

number = 42
padded = "{:05d}".format(number)  # Pad to 5 digits
print(padded)  # Output: 00042

4. Using rjust()

The rjust() method right-justifies a string and pads with a specified character (default is space, but you can use ‘0’).

number = 42
padded = str(number).rjust(5, '0')  # Pad to 5 digits with zeros
print(padded)  # Output: 00042

Handling Negative Numbers

For negative numbers, zfill(), f-strings, and rjust() include the minus sign in the length count:

number = -42
print(str(number).zfill(5))  # Output: -0042
print(f"{number:05d}")      # Output: -0042
print(str(number).rjust(5, '0'))  # Output: -0042

If you want the minus sign excluded from the padding length, you’ll need custom logic:

number = -42
sign = '-' if number < 0 else ''
padded = f"{abs(number):04d}"  # Pad absolute value to 4 digits
print(sign + padded)  # Output: -0042

Key Points

  • Choose zfill() or f-strings for simplicity and readability.
  • Ensure the target length is sufficient to accommodate the number’s digits (and sign, if negative).
  • These methods work for converting integers to fixed-length strings, often used for formatting IDs, timestamps, or display purposes.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注