Here are some common string methods.
.lower() method returns the string in lower case:
a = "Hello World"
print(a.lower())
# Output: hello world
.upper() method returns the string in upper case:
a = "Hello World"
print(a.upper())
# Output: HELLO WORLD
.title() returns the string in title case, which means the first letter of each word is capitalized.
a = "hello world"
print(a.title())
# Output: Hello World
.split() splits a string into a list of items:
string_name.split(delimiter)
Example 1
a = "Hello World"
print(a.split())
# Output: ['Hello', 'World']
Example 2
students = "Jane,Anna,John,Peter"
print(students.split(","))
# Output: ['Jane', 'Anna', 'John', 'Peter']
We can also split strings using escape sequences.
long_string = \
"""Hello
This is a long paragraph
To split this
We use escape sequences"""
lst = long_string.split('\n')
print(lst)
# Output: ['Hello', 'This is a long paragraph', 'To split this', 'We use escape sequences']
.join() joins a list of strings together with a given delimiter.
Syntax
"delimiter".join(list_of_strings)
For example
lst = ["The", "weather", "is", "sunny"]
print(" ".join(lst))
# Output: The weather is sunny
.strip() removes characters from the beginning and end of a string.
We can specify a set of characters to be stripped with a string argument. With no arguments to the method, whitespace is removed.
a = " Hello World "
print(a.strip())
.replace() method replaces a string with another string.
Syntax
string_name.replace(character_being_replaced, new_character)
For example
a = "Hello World"
print(a.replace("H", "J"))
# Output: Jello World
.find() searches the string for a specific value and returns the first index value where that value is located.
a = "Hello World"
print(a.find("W"))
# Output: 6
.format() formats specified values in a string.
Syntax
string.format(value1, value2...)
For example
def favorite_food(topping, food):
return "My favorite food is {} {}.".format(topping, food)
print(favorite_food("vanilla", "ice-cream"))
# Output: My favorite food is vanilla ice-cream.