5 Useful Python String Methods

Hi!, my name is Aya Bouchiha, on this beautiful day, I'm going to share with you 5 useful string methods in Python.

Firstly, we need to know that all python methods do not change the original value of the string, they return new values.

startswith()

startswith(prefix, start = 0, end = len(str) - 1): checks if a string starts with a giving value.

Parameters of startswith

  • prefix: to check that the string starts

  • start = 0: the starting index where the giving prefix is needed to be checked.

  • end = len(str) - 1: the ending index where the giving needs to be checked.

phone_number = '+212123456789';
print(phone_number.startswith('34',1)) # False
print(phone_number.startswith('+212')) # True
print(phone_number.startswith('56', 8)) # True
print(phone_number.startswith('78', 10, 12)) # True

replace()

replace(old_value, new_value, count): replace a specific substring with a giving new value.

parameters

  • old_value: the specific substring that you want to replace it
  • new_value: the new value to replace it with old_value
  • count: (optional) number specifying how many occurrences of the old value you want to replace. Default is all occurrences
country_code = '212'
user_phone_number = f'{country_code}6123452129'
# 2126123452129
print(user_phone_number) 
# 066123452129
print(user_phone_number.replace(country_code, '06', 1))

title()

title(): this string method converts each word's first character to uppercase.

article_slug = '5-html-tags-that-almost-nobody-knows'
article_title = article_slug.replace('-',' ').title()
# 5 HTML Tags That Almost Nobody Knows
print(article_title)

upper(), lower()

upper(): converts string's characters to uppercase
lower(): converts string's characters to lowercase

full_name = 'Aya Bouchiha'
print(full_name.upper()) # AYA BOUCHIHA
print(full_name.lower()) # aya bouchiha

find()

find(valueToSearch, startIndex=0, endIndex=len(str)): returns the index of the first occurence of the giving substring. It is similar to index(), but it returns -1 instead of raising an exception.

Parameters

  • valueToSearch: string to search
  • startIndex = 0: index to start searching
  • endIndex = len(str): index to end searching
message = 'Tanger is a beautiful city'
address = 'Tanger, Morocco'
language = 'en-us' 
print(message.find('beautiful')) # 12
print(address.find('Morocco', len(address) - 7)) # 8
print(language.find('en', 0, 2)) # 0
print(language.find('fr', 0, 2)) # -1

Summary

  • startswith: checks if a string starts with a giving value.
  • title: converts each word's first character to uppercase.
  • replace: replace a specific substring with a giving new value.
  • upper, lower: converts string's characters to uppercase, lowercase
  • find: returns the index of the first occurrence of the giving substring.

Have an amazing day!

18