Difficulty: Beginner
Python strings come with a rich set of built-in methods. These methods do not modify the original string (since strings are immutable) but return a new string with the requested transformation applied.
Case-changing methods include upper() which converts all characters to uppercase, lower() which converts to lowercase, title() which capitalizes the first letter of each word, and capitalize() which capitalizes only the first character of the string. These are essential for normalizing user input - for example, comparing emails in a case-insensitive way.
Whitespace handling is done with strip(), lstrip(), and rstrip(). The strip() method removes leading and trailing whitespace (or specified characters) from a string. This is particularly important when processing user input or reading from files where extra spaces or newlines may appear.
Searching and modifying methods include find() which returns the index of the first occurrence of a substring (or -1 if not found), count() which returns the number of non-overlapping occurrences, replace() which substitutes all occurrences of one substring with another, split() which breaks a string into a list of substrings based on a delimiter, and join() which combines a list of strings into one string with a specified separator.
text = "hello, World!"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
upper() converts all characters to uppercase, lower() to lowercase, title() capitalizes each word, and capitalize() only capitalizes the first character of the whole string.
raw_input = " apple, banana, cherry "
cleaned = raw_input.strip()
fruits = cleaned.split(", ")
result = " | ".join(fruits)
print(cleaned)
print(fruits)
print(result)
strip() removes leading/trailing whitespace. split(', ') breaks on the comma-space delimiter. join() connects list items with ' | '.
text = "the cat sat on the mat"
print(text.find("cat"))
print(text.find("dog"))
print(text.count("the"))
print(text.replace("cat", "dog"))
find() returns 4 (the index where 'cat' starts) or -1 when the substring is not found. count() finds 2 occurrences of 'the'. replace() substitutes 'cat' with 'dog'.
data = " John DOE "
result = data.strip().lower().replace(" ", "_")
print(result)
Methods can be chained because each one returns a new string. Here we strip whitespace, convert to lowercase, and replace spaces with underscores.
upper, lower, strip, split, join, replace, find, count