Python provides a wide range of built-in methods for string manipulation. Here are some of the most commonly used methods:
len(): returns the length of a string
string = "Hello World"
print(len(string)) # Output: 11
lower(): returns a lowercase version of a string
string = "Hello World"
print(string.lower()) # Output: hello world
upper(): returns an uppercase version of a string
string = "Hello World"
print(string.upper()) # Output: HELLO WORLD
strip(): removes leading and trailing whitespace from a string
string = " Hello World "
print(string.strip()) # Output: "Hello World"
split(): splits a string into a list of substrings, based on a specified delimiter
string = "Hello,World"
print(string.split(",")) # Output: ['Hello', 'World']
replace(): replaces all occurrences of a substring with another substring
string = "Hello World"
print(string.replace("World", "Python")) # Output: "Hello Python"
find(): searches for a substring within a string, and returns the index of the first occurrence
string = "Hello World"
print(string.find("o")) # Output: 4
startswith(): returns True if a string starts with a specified substring, otherwise False
string = "Hello World"
print(string.startswith("Hello")) # Output: True
endswith(): returns True if a string ends with a specified substring, otherwise False
string = "Hello World"
print(string.endswith("World")) # Output: True
join(): joins a list of strings into a single string, using a specified separator
my_list = ['Hello', 'World']
separator = ', '
print(separator.join(my_list)) # Output: "Hello, World"
In summary, Python provides a wide range of built-in methods for string manipulation, such as len(), lower(), upper(), strip(), split(), replace(), find(), startswith(), endswith(), and join(). These methods can be used to manipulate strings in various ways, such as converting between uppercase and lowercase, splitting and joining substrings, and searching for and replacing substrings.