Python offers several methods for formatting strings, allowing developers to embed dynamic data within text. The traditional % operator is one approach, supporting format specifiers like %d for integres, %s for strings, and %f for floating-point numbers. For instance, to format a phone bill messsage:
name = "Alice"
cost = 88.88
balance = 66.60
percent = 77.77
year = 2024
month = 3
day = 8
message = "Dear %s, your monthly phone bill is %.2f yuan, with an account balance of %.2f yuan. You've surpassed %.2f%% of users nationwide. Please top up if your balance is low. Date: %d-%02d-%02d."
print(message %% (name, cost, balance, percent, year, month, day))
A more modern and often preferred method is the format() string method. It uses curly braces {} as placeholders, which can be indexed or named. Formatting specifiers are added after a colon, such as {:.2f} for floating-point numbers with two decimal places or {:02d} for integers padded with a leading zero to occupy two digits.
message_formatted = "Dear {0}, your monthly phone bill is {1:.2f} yuan, with an account balance of {2:.2f} yuan. You've surpassed {3:.2f}% of users nationwide. Please top up if your balance is low. Date: {4}-{5:02d}-{6:02d}."
print(message_formatted.format(name, cost, balance, percent, year, month, day))
# Using named placeholders
message_named = "Dear {n}, your monthly phone bill is {c:.2f} yuan, with an account balance of {b:.2f} yuan. You've surpassed {p:.2f}% of users nationwide. Please top up if your balance is low. Date: {y}-{m:02d}-{d:02d}."
print(message_named.format(n=name, c=cost, b=balance, p=percent, y=year, m=month, d=day))
Python 3.6+ introduced f-strings (formatted string literals), which provide a concise and readable way to embed expresssions inside string literals. They are prefixed with f or F.
message_fstring = f"Dear {name}, your monthly phone bill is {cost:.2f} yuan, with an account balance of {balance:.2f} yuan. You've surpassed {percent:.2f}% of users nationwide. Please top up if your balance is low. Date: {year}-{month:02d}-{day:02d}."
print(message_fstring)
Beyond formatting, Python's string objects offer a rich set of manipulation methods.
Whitespace Removal:
strip(): Removes leading and trailing whitespace.lstrip(): Removes leading whitespace.rstrip(): Removes trailing whitespace.
spaced_string = ' Example String '
print(spaced_string.strip())
print(spaced_string.lstrip())
print(spaced_string.rstrip())
Replacement:
replace(old, new): Returns a copy of the string with all occurrences of substringoldreplaced bynew.
original = 'Apple, Banana, Apple'
replaced = original.replace('Apple', 'Orange')
print(replaced)
Splitting:
split(separator, maxsplit): Splits the string into a list of substrings based on a delimiter.maxsplitlimits the number of splits.
multi_word = 'one-two-three four five'
parts_dash = multi_word.split('-', 1)
print(parts_dash)
import re
# Using regex to split by '-' or spaces, handling multiple delimiters
parts_complex = re.split(r'[-\s]+', 'one- two - three four five'.strip())
print(parts_complex)
Counting Substrings:
count(sub[, start[, end]]): Returns the number of non-overlapping occurrences of substringsub.
text = 'abababa'
count_a = text.count('a', 0, 5) # Count 'a' from index 0 up to (not including) 5
print(count_a)
Finding Substrings:
index(sub[, start[, end]]): Returns the lowest index in the string where substringsubis found. RaisesValueErrorif not found.
search_text = 'hello world hello'
first_hello = search_text.index('hello')
print(first_hello)
second_hello = search_text.index('hello', first_hello + 1) # Start search after the first 'hello'
print(second_hello)
Character Type Checks:
isdigit(): ReturnsTrueif all characters are digits and there is at least one character,Falseotherwise.islower(): ReturnsTrueif all cased characters are lowercase and there is at least one cased character,Falseotherwise.isupper(): ReturnsTrueif all cased characters are uppercase and there is at least one cased character,Falseotherwise.
print('12345'.isdigit())
print('abcde'.islower())
print('ABCDE'.isupper())
print('abc123'.islower())
print('ABC123'.isupper())
Case Conversion:
lower(): Converts all uppercase characters to lowercase.upper(): Converts all lowercase characters to uppercase.
print('HeLLo'.lower())
print('wORLd'.upper())
Prefix and Suffix Checks:
startswith(prefix[, start[, end]]): ReturnsTrueif the string starts with the specified prefix.endswith(suffix[, start[, end]]): ReturnsTrueif the string ends with the specified suffix.
filename = 'document.txt'
print(filename.startswith('doc'))
print(filename.endswith('.txt'))
Membership Testing:
in: ReturnsTrueif a substring is found within the string.not in: ReturnsTrueif a substring is not found within the string.
sentence = 'Python is fun'
print('is' in sentence)
print('java' not in sentence)
String Length:
len(string): Returns the number of characters in the string.
print(len(sentence))
Slicing:
String slicing extracts a portion of the string using [start:stop:step]. start is inclusive, stop is exclusive. step determines the increment.
my_string = 'abcdefghij'
# Slice from index 1 up to (not including) index 4
print(my_string[1:4]) # Output: bcd
# Slice with a step of 2 (every second character)
print(my_string[::2]) # Output: acegi
# Reverse the string using a step of -1
print(my_string[::-1]) # Output: jihgfedcba
# Negative indexing: slice from the 3rd to last character up to (not including) the last character
print(my_string[-3:-1]) # Output: hi