Python provides many built-in string methods to manipulate and analyze text data. Since strings are immutable, these methods always return a new string (or value) instead of changing the original.
Common things you can do with string methods:
variable.method(arguments), for example: text.upper().upper(), lower(), title(), capitalize().count(), find(), startswith(), endswith().strip(), lstrip(), rstrip(), replace().split() turns a string into a list; join() does the opposite.The general syntax for calling a string method is:
result = string_value.method_name(optional_arguments)
For example:
message = "hello world"
upper_msg = message.upper() # returns "HELLO WORLD"
You can also chain string methods:
clean_name = " alice ".strip().title() # "Alice"
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.title()) # Hello World
print(text.capitalize()) # Hello world
text = "hello world"
print(text.count("l")) # 3
print(text.find("world")) # 6
print(text.startswith("hello")) # True
print(text.endswith("world")) # True
text = " hello world "
print(text.strip()) # "hello world"
print(text.lstrip()) # "hello world "
print(text.rstrip()) # " hello world"
print(text.replace("world", "Python")) # " hello Python "
text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
joined = "-".join(fruits)
print(joined) # apple-banana-cherry
upper() prints HELLO WORLD (all letters uppercase).lower() prints hello world (all letters lowercase).title() prints Hello World (first letter of each word uppercase).capitalize() prints Hello world (only the first character of the whole string uppercase).count("l") returns 3 because there are three l characters.find("world") returns 6 which is the starting index of "world".startswith("hello") returns True because the string begins with "hello".endswith("world") returns True because the string ends with "world".strip() removes spaces from both ends.lstrip() removes spaces from the left side only.rstrip() removes spaces from the right side only.replace("world", "Python") changes the word world to Python.split(",") breaks the string into a list of substrings: ['apple', 'banana', 'cherry']."-".join(fruits) joins the list back into a single string apple-banana-cherry with - between words.text.strip().upper() for powerful one-line transformations.startswith() and endswith() for clean and readable prefix/suffix checks.join(), remember it is called on the separator string, not on the list: "-".join(list_of_strings)."a" appears in a long sentence using count().replace() to change a name in a sentence (e.g., replace "world" with "Python")."red,green,blue"), split it into a list, then join it back using " | " as a separator.strip(), lstrip(), and rstrip() on strings that have spaces or tabs at the edges.