String Methods

Here are some common string methods.

1. lower()

.lower() method returns the string in lower case:

a = "Hello World"
print(a.lower())
# Output: hello world

2. upper()

.upper() method returns the string in upper case:

a = "Hello World"
print(a.upper())
# Output: HELLO WORLD

3. title()

.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

4. split()

.split() splits a string into a list of items:

string_name.split(delimiter)
  • If no argument is passed, the default behavior is to split on whitespace.
  • If an argument is passed to the method, that value is used as the delimiter on which to split the string.

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.

  • \n Newline allows us to split a multi-line string by line breaks
  • \t Horizontal Tab allows us to split a string by tabs
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']

5. join()

.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

6. strip()

.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())

7. replace()

.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

8. find()

.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

9. format()

.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.