String methods and f-strings
Strings come with dozens of methods. A method is called with a dot after the value: text.upper(). Since strings are immutable, every method returns a new string and leaves the original alone.
Changing case
s = "machine Learning"
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
print(s.swapcase())Trimming whitespace
raw = " padded "
print(repr(raw.strip()))
print(repr(raw.lstrip()))
print(repr(raw.rstrip()))strip() also accepts characters to remove: "xxhixx".strip("x") gives "hi".
Searching
s = "data science is data driven"
print(s.find("data")) # index of first match, -1 if missing
print(s.rfind("data")) # last match
print(s.count("data"))
print(s.startswith("data"))
print(s.endswith("driven"))
print(s.index("science")) # like find, but raises ValueError if missingReplacing
s = "I like Java"
print(s.replace("Java", "Python"))
print("aaa".replace("a", "b", 2)) # replace at most 2 occurrencesSplitting and joining
split() turns a string into a list; join() does the reverse.
csv = "apple,banana,cherry"
parts = csv.split(",")
print(parts)
words = "one two three".split() # no argument splits on any whitespace
print(words)
print(" | ".join(parts))
print("".join(["a", "b", "c"]))Checking content
print("12345".isdigit())
print("hello".isalpha())
print("hello123".isalnum())
print(" ".isspace())
print("HELLO".isupper())f-strings
An f-string is a string with an f before the opening quote. Anything inside { } is evaluated as Python.
name = "Sara"
marks = 87.456
print(f"{name} scored {marks} marks")
print(f"{name} scored {marks:.1f} marks") # one decimal place
print(f"{name!r}") # repr of the value
print(f"{2 ** 10}") # any expression worksFormat specs
The part after the colon controls how the value looks.
n = 1234567.891
print(f"{n:,.2f}") # thousands separator, 2 decimals
print(f"{0.256:.1%}") # percentage
print(f"{42:05d}") # zero padded to width 5
print(f"{'left':<10}|") # left aligned in 10 characters
print(f"{'right':>10}|")
print(f"{'mid':^10}|")Debugging shortcut
{expr=} prints the expression and its value together:
x = 10
y = 3
print(f"{x=}, {y=}, {x * y=}")The older format() method
You will still see this in existing code. It works the same way but is more verbose.
print("{} scored {:.1f}".format("Sara", 87.456))
print("{name} is {age}".format(name="Amit", age=20))Practice
- Take the string
" Machine Learning With Python ", strip it, lowercase it and replace spaces with hyphens to make a URL slug. - Given
price = 1499.5, print it asRs 1,499.50using an f-string. - Count how many times the letter "a" appears in
"banana bandana".
