Python String Methods
In Python, strings are sequences of characters that can be manipulated using a variety of built-in methods. In this tutorial, we will explore some of the most popular string methods
# TldR
s = 'hello, world!'
print(s.capitalize()) # Output: 'Hello, world!'
s = 'hello, world!'
print(s.upper()) # Output: 'HELLO, WORLD!'
s = 'HELLO, WORLD!'
print(s.lower()) # Output: 'hello, world!'
s = 'Hello, world! How are you today?'
print(s.split()) # Output: ['Hello,', 'world!', 'How', 'are', 'you', 'today?']
s = 'Hello, world!'
print(s.replace('world', 'Python')) # Output: 'Hello, Python!'
s = ','
lst = ['Hello', 'world', 'how', 'are', 'you']
print(s.join(lst)) # Output: 'Hello,world,how,are,you'
s = ' Hello, world! '
print(s.strip()) # Output: 'Hello, world!'
s = 'Hello, world!'
print(s.find('world')) # Output: 7
str.capitalize()
Returns a new string with the first letter of the original string capitalized and all other letters lowercase.
# Example 1: Capitalizing the first letter of a string that contains the name of a person
name = 'john smith'
print(name.capitalize()) # Output: 'John smith'
# Example 2: Capitalizing the first letter of each word in a string
s = 'this is a test string'
print(' '.join([word.capitalize() for word in s.split()])) # Output: 'This Is A Test String'
str.upper()
Returns a new string with all the letters in the original string converted to uppercase.
# Example 1: Converting a string to uppercase before comparing it to another string
password = 'Abcd1234'
input_password = 'abcd1234'
if input_password.upper() == password.upper():
print('Passwords match')
else:
print('Passwords do not match')
# Example 2: Converting a string to uppercase before storing it in a database
s = 'Hello, world!'
db.execute('INSERT INTO table (column) VALUES (?)', (s.upper(),))
str.lower():
Returns a new string with all the letters in the original string converted to lowercase.
# Example 1: Converting a string to lowercase before comparing it to another string email = '[email protected]' input_email = '[email protected]' if input_email.lower() == email.lower(): print('Emails match') else: print('Emails do not match') # Example 2: Converting a string to lowercase before storing it in a database s = 'Hello, world!' db.execute('INSERT INTO table (column) VALUES (?)', (s.lower(),))
str.split()
Splits the string into a list of substrings using a specified delimiter. If no delimiter is specified, the default delimiter is any sequence of whitespace characters.
# Example 1: Splitting a string into a list of words
s = 'Hello, world! How are you today?'
words = s.split()
print(words) # Output: ['Hello,', 'world!', 'How', 'are', 'you', 'today?']
# Example 2: Splitting a string into a list of lines
s = 'Hello, world!\nHow are you today?\nI am fine, thank you.'
print(s.split('\n')) # Output: ['Hello, world!', 'How are you today?', 'I am fine, thank you.']
# Example 3: Splitting a string into a list of values using a specific delimiter
s = '1,2,3,4,5'
print(s.split(',')) # Output: ['1', '2', '3', '4', '5']
str.replace()
Returns a new string with all occurrences of a specified substring replaced with a different substring.
# Example 1: Replacing all occurrences of a substring with a different substring
s = 'Hello, world! How are you today?'
print(s.replace('world', 'Python')) # Output: 'Hello, Python! How are you today?'
# Example 2: Replacing multiple substrings with different substrings
s = 'Hello, world! How are you today?'
s = s.replace
str.join()
Returns a new string by joining a sequence of strings using the original string as the delimiter.
# Example 1: Joining a list of words with a space character as the delimiter words = ['Hello', 'world', 'how', 'are', 'you'] s = ' '.join(words) print(s) # Output: 'Hello world how are you' # Example 2: Joining a list of values with a comma and a space as the delimiter values = [1, 2, 3, 4, 5] s = ', '.join(str(v) for v in values) print(s) # Output: '1, 2, 3, 4, 5' # Example 3: Joining a list of strings with a newline character as the delimiter lines = ['Hello, world!', 'How are you today?', 'I am fine, thank you.'] s = '\n'.join(lines) print(s) # Output: 'Hello, world!\nHow are you today?\nI am fine, thank you.'
str.strip()
Returns a new string with leading and trailing whitespace characters removed.
# Example 1: Removing leading and trailing whitespace from a string
s = ' Hello, world! '
print(s.strip()) # Output: 'Hello, world!'
# Example 2: Removing leading and trailing characters from a string
s = '####Hello, world!####'
print(s.strip('#')) # Output: 'Hello, world!'
# Example 3: Removing leading and trailing characters from a list of strings
lines = ['####Hello, world!####', '####How are you today?####', '####I am fine, thank you.####']
lines = [line.strip('#') for line in lines]
print(lines) # Output: ['Hello, world!', 'How are you today?', 'I am fine, thank you.']
str.find()
Returns the index of the first occurrence of a specified substring in the string, or -1 if the substring is not found.
# Example 1: Searching for a substring in a string and printing its index
s = 'Hello, world! How are you today?'
index = s.find('world')
if index >= 0:
print('Substring found at index', index)
else:
print('Substring not found')
# Example 2: Searching for a substring in a string and printing a message if it is not found
s = 'Hello, world! How are you today?'
index = s.find('Python')
if index >= 0:
print('Substring found at index', index)
else:
print('Substring not found')
# Example 3: Searching for a substring in a list of strings and printing the index of the first occurrence
lines = ['Hello, world!', 'How are you today?', 'I am fine, thank you.']
for i, line in enumerate(lines):
index = line.find('world')
if index >= 0:
print('Substring found at index', i)
break
else:
print('Substring not found')
