Python - Functions - String

len(): This function is used to find the length of a string.

string = "Hello World"
print(len(string)) #Output: 11

upper(): This function is used to convert a string to uppercase.

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

lower(): This function is used to convert a string to lowercase.

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

replace(): This function is used to replace a substring with another substring in a string.

string = "Hello World"
print(string.replace("World", "Universe")) #Output: Hello Universe

strip(): This function is used to remove any whitespace characters from the beginning or end of a string.

string = "  Hello World  "
print(string.strip()) #Output: Hello World

split(): This function is used to split a string into a list of substrings based on a separator.

string = "Hello,World"
print(string.split(",")) #Output: ['Hello', 'World']

join(): This function is used to join a list of substrings into a single string using a separator.

list_of_strings = ["Hello", "World"]
separator = "-"
print(separator.join(list_of_strings)) #Output: Hello-World

capitalize(): This function is used to capitalize the first letter of a string.

string = "hello world"
print(string.capitalize()) #Output: Hello world

isalpha(): This function is used to check if a string contains only alphabetic characters.

string = "HelloWorld"
print(string.isalpha()) #Output: True

isnumeric(): This function is used to check if a string contains only numeric characters.

string = "12345"
print(string.isnumeric()) #Output: True