Module: M1-R5: Information Technology Tools and Network Basics
Chapter: Ch1 Computer Intro
Python provides a wide range of built-in string functions to manipulate, format, and check strings.
Returns the number of occurrences of a substring.
text = 'hello world'
print(text.count('l'))Output:
3Finds first/last index of a substring.
text = 'hello world'
print(text.find('o'))
print(text.rfind('o'))Output:
4
7Capitalizes the first character of the string.
text = 'hello world'
print(text.capitalize())Output:
Hello worldCapitalizes the first letter of each word.
text = 'hello world'
print(text.title())Output:
Hello WorldConverts string to lowercase.
text = 'HELLO WORLD'
print(text.lower())Output:
hello world
Converts string to uppercase.
text = 'hello world'
print(text.upper())Output:
HELLO WORLDSwaps the case of each character.
text = 'Hello World'
print(text.swapcase())Output:
hELLO wORLDChecks if all characters are lowercase.
text = 'hello'
print(text.islower())Output:
TrueChecks if all characters are uppercase.
text = 'HELLO'
print(text.isupper())Output:
TrueChecks if string is in title case.
text = 'Hello World'
print(text.istitle())Output:
True
Replaces a substring with another.
text = 'hello world'
print(text.replace('world','Python'))Output:
hello PythonRemoves leading and trailing spaces.
text = ' hello '
print(text.strip())Output:
helloRemoves leading spaces.
text = ' hello '
print(text.lstrip())Output:
hello Removes trailing spaces.
text = ' hello '
print(text.rstrip())Output:
helloSplits string into a list.
text = 'hello world'
print(text.split())Output:
['hello', 'world']
Splits string into 3 parts around a separator.
text = 'hello world'
print(text.partition(' '))Output:
('hello', ' ', 'world')Joins iterable elements with string as separator.
words = ['hello','world']
print('-'.join(words))Output:
hello-worldChecks if string contains only whitespace.
text = ' '
print(text.isspace())Output:
TrueChecks if string contains only letters.
text = 'hello'
print(text.isalpha())Output:
TrueChecks if string contains only digits.
text = '123'
print(text.isdigit())Output:
True
Checks if string is alphanumeric.
text = 'hello123'
print(text.isalnum())Output:
TrueChecks if string starts with a substring.
text = 'hello world'
print(text.startswith('hello'))Output:
TrueChecks if string ends with a substring.
text = 'hello world'
print(text.endswith('world'))Output:
TrueEncodes string to bytes.
text = 'hello world'
encoded = text.encode('utf-8')
print(encoded)Output:
b'hello world'Decodes bytes to string.
decoded = encoded.decode('utf-8')
print(decoded)Output:
hello world