Skip to content

String manipulation

Testing facts about a string

The str type in Python provides a variety of methods that test a given string for the presence of certain properties and return True or False. These methods can be useful in conditional expressions.

  • Check for the presence of a given prefix or set of prefixes or a given suffix or set of suffixes
    >>> text = "the quick brown fox"
    >>> text.startswith("a")
    False
    >>> text.startswith(("a", "the"))
    True
    >>> text.endswith("dog")
    False
    >>> text.endswith("x")
    True
    
  • Predicates useful for input validation
    >>> text = input("What is your age: ")
    What is your age: 30
    >>> text.isalpha()
    False
    >>> text.isalnum()
    True
    >>> text.isdigit()
    True
    >>> text.isnumeric()
    True
    

Searching and replacing

>>> text = "the quick brown fox"
>>> "quick" in text
True
>>> text.find("quick")
4
>>> text.find("lazy")
-1
>>> text.replace("quick", "lazy")
'the lazy brown fox'
>>> text.count("quick")
1

Splitting and joining

>>> text = "\n      the quick brown fox"
>>> print(text)

    the quick brown fox
>>> text = text.strip()
>>> text.split()
['the', 'quick', 'brown', 'fox']
>>> text.split("quick")
['the', 'brown fox']
>>> '_'.join(text.split())
'the_quick_brown_fox'

f-strings

It is common to build strings from values stored in variables. f-strings provide a convenient way to achieve this.

>>> item = "oranges"
>>> price = 1.5
>>> quantity = 5
>>> print(f"You bought {quantity} {item}")
You bought 5 oranges
>>> print(f"Total: ${quantity * price:.2f}")
Total: $7.50

The :.2f in the previous example is a formatting specifier. It tells Python to format the value as a decimal number with two decimal places.

In addition to specifying the type and precision of a number, the Python formatting mini-language lets you customize other things such as width, alignment, padding, etc.

>>> amount = 50
>>> f"{amount:>5}"
'   50'
>>> f"{amount:<5}:
'50   '
>>> f"{amount:>5.2f}"
'50.00'
>>> f"{amount:*>5}"
'***50'
>>> f"{amount:*^5}"
'*50**'

Formatting columns of text

# invoice.py
print("your invoice".upper().center(34))    # str also can center!
print()
print(f"{'Item':<10}{'Quantity':>9}{'Price':>6}{'Subtotal':>9}")
print("-" * 34)
print(f"{'Printer':<10}{1:>9}{45.99:>6.2f}{45.99:>9.2f}")
print(f"{'Cartridge':<10}{5:>9}{10.99:>6.2f}{5 * 10.99:>9.2f}")
print("-" * 34)
print(f"{f"${5 * 10.99 + 45.99}":>34}") # you can nest them!
           YOUR INVOICE

Item       Quantity Price Subtotal
----------------------------------
Printer           1 45.99    45.99
Cartridge         5 10.99    54.95
----------------------------------
                           $100.94