String Methods

Here are some common string methods.

1. lower()

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

a = "Hello World"
# Output: hello world

2. upper()

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

a = "Hello World"

3. title()

.title() returns the string in title case, which means the first letter of each word is capitalized.

a = "hello world"
# Output: Hello World

4. split()

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

  • 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"
# Output: ['Hello', 'World']

Example 2

students = "Jane,Anna,John,Peter"
# 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 = \
This is a long paragraph
To split this
We use escape sequences"""

lst = long_string.split('\n')

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



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   "

7. replace()

.replace() method replaces a string with another string.


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"
# Output: 6

9. format()

.format() formats specified values in a string.


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.