Python string methods
Created By: chatGPT
In Python, strings are immutable sequences of characters, and there are several built-in methods that can be used to manipulate them. Here, I'll highlight some of the most commonly used string methods with examples.
1.
str.lower()
: Converts all characters in the string to lowercase.example_string = 'Hello World'
lowercase_string = example_string.lower()
print(lowercase_string) # Output: hello world
2.
str.upper()
: Converts all characters in the string to uppercase.example_string = 'Hello World'
uppercase_string = example_string.upper()
print(uppercase_string) # Output: HELLO WORLD
3.
str.title()
: Capitalizes the first character of each word in the string.example_string = 'hello world'
title_string = example_string.title()
print(title_string) # Output: Hello World
4.
str.strip()
: Removes leading and trailing whitespace characters from the string.example_string = ' Hello World '
stripped_string = example_string.strip()
print(stripped_string) # Output: 'Hello World'
5.
str.split()
: Splits the string into a list of substrings based on a delimiter (default is space).example_string = 'Hello World'
split_string = example_string.split()
print(split_string) # Output: ['Hello', 'World']
6.
str.join()
: Joins a list of strings into a single string using a specified separator.words = ['Hello', 'World']
joined_string = ' '.join(words)
print(joined_string) # Output: 'Hello World'
7.
str.find()
: Returns the lowest index in the string where a substring is found. Returns -1 if not found.example_string = 'Hello World'
index = example_string.find('World')
print(index) # Output: 6
8.
str.replace()
: Replaces occurrences of a substring with another substring.example_string = 'Hello World'
replaced_string = example_string.replace('World', 'Python')
print(replaced_string) # Output: 'Hello Python'
9.
str.startswith()
: Checks if the string starts with the specified substring. Returns True or False.example_string = 'Hello World'
result = example_string.startswith('Hello')
print(result) # Output: True
10.
str.endswith()
: Checks if the string ends with the specified substring. Returns True or False.example_string = 'Hello World'
result = example_string.endswith('World')
print(result) # Output: True