SoFunction
Updated on 2025-04-17

Python string alignment and judgment method summary

Python ljust(), rjust() and center() methods

1. ljust() method: left aligned

The ljust() method is used to align the string left and fill it to the specified length with the specified character (default is a space).

# Basic syntax: (width[, fillchar])# width: Total length of string# fillchar: fill characters (optional, default is space)
# Example 1: Fill with default spacestext = "Python"
result = (10)
print(f"[{result}]")
# Output: [Python]
# Example 2: Fill with custom charactersresult = (10, '*')
print(f"[{result}]")
# Output: [Python****]

2. rjust() method: right-align

The rjust() method is used to right-align the string and fill it to the specified length with the specified character (default is a space).

# Basic syntax: (width[, fillchar])
# Example 1: Fill with default spacestext = "Python"
result = (10)
print(f"[{result}]")
# Output: [Python]
# Example 2: Fill with custom charactersresult = (10, '0')
print(f"[{result}]")
# Output: [0000Python]
# Example 3: Digital Formatprice = "99"
formatted_price = (6, '0')
print(formatted_price)
# Output: 000099

3. Center() method: center aligned

The center() method is used to center the string and fill it to the specified length with the specified character (default is space).

# Basic syntax: (width[, fillchar])
# Example 1: Fill with default spacestext = "Python"
result = (10)
print(f"[{result}]")
# Output: [Python]
# Example 2: Fill with custom charactersresult = (10, '-')
print(f"[{result}]")
# Output: [--Python--]

4. Practical application scenarios

# Create simple text tablesdef print_table_row(item, price, width=20):
    item_col = (width)
    price_col = str(price).rjust(8)
    print(f"{item_col}{price_col}")

# Print the table headerprint("Product List".center(28, '='))
print_table_row("commodity", "price")
print("-" * 28)

# Print dataprint_table_row("apple", 5.5)
print_table_row("banana", 3.8)
print_table_row("orange", 4.2)

#Output:# ============ Product List============# Product Price# ----------------------------
# Apple 5.5# Banana 3.8# Orange 4.2

Python startswith() and endswith() methods

1. startswith() method: judge the beginning of a string

The startswith() method is used to check whether the string starts with the specified prefix.

# Basic syntax: (prefix[, start[, end]])# prefix: The prefix to be checked can be a string or a tuple# start: optional, the location to start the check# end: optional, the location where the check is finished
# Example 1: Basic usagefilename = ""
print(("ex"))  # Output: Trueprint(("py"))  #Output: False
# Example 2: Specify the check rangetext = "Hello, Python!"
print(("Python", 7))  # Output: True
# Example 3: Multiple prefixes (using tuples)filename = ""
print((("doc", "txt", "pdf")))  # Output: True

2. endswith() method: judge the end of a string

The endswith() method is used to check whether the string ends with the specified suffix.

# Basic syntax: (suffix[, start[, end]])
# Example 1: Basic usagefilename = ""
print((".txt"))  # Output: Trueprint((".pdf"))  #Output: False
# Example 2: Specify the check rangetext = "Hello, Python!"
print(("Python", 0, 12))  # Output: True
# Example 3: Multiple suffixes (using tuples)filename = ""
print(((".doc", ".txt", ".pdf")))  # Output: True

3. Practical application scenarios

# Example 1: File Type Checkdef is_image_file(filename):
    return ().endswith(('.png', '.jpg', '.jpeg', '.gif'))

# Test file typefiles = ['', '', '', '']
for file in files:
    if is_image_file(file):
        print(f"{file} It's a picture file")
    else:
        print(f"{file} 不It's a picture file")

# Example 2: URL protocol checkingdef check_url_protocol(url):
    if ('https://'):
        return "Security Connection"
    elif ('http://'):
        return "Unsecure connection"
    else:
        return "Unknown Agreement"

# Test URLurls = [
    '',
    '',
    'ftp://'
]

for url in urls:
    print(f"{url}: {check_url_protocol(url)}")

Summarize

This tutorial introduces in detail the string alignment methods (ljust, rjust, and center) and string judgment methods (startswith and endswith) in Python:

  1. String alignment method

    • ljust(): left-align text
    • rjust(): Right-align text
    • center(): center aligning text
      These methods are very useful in scenarios such as formatting output, creating text tables, etc.
  2. String judgment method

    • startswith(): Check the beginning of the string
    • endswith(): Check the end of the string
      These methods are often used in scenarios such as file type checking and URL verification.

Mastering these methods can help you better process text data, create formatted output, and perform string matching and verification.