Python uses the string formatting method to set the fixed length of the string

This can be achieved using the string format() method or f-string.

Use the format() method:

string = "hello"
formatted_string = "{:<10}".format(string)
print(formatted_string)  # 输出:"hello     "

In the above example, {:<10} means to align the string to the left and occupy a width of 10 characters.

Use f-string:

string = "hello"
formatted_string = f"{
      
      string:<10}"
print(formatted_string)  # 输出:"hello     "

In the above example, f"{string:<10}"it means that the string is left aligned and occupies a width of 10 characters.

This fixes the string to the specified length, padding spaces on the right to the specified length if the original string length is less than the specified length. You can also use other fill characters as needed, such as > to indicate right alignment, or other characters for padding.

Guess you like

Origin blog.csdn.net/qq_16792139/article/details/132673489