Comprehensive Guide to Strings in Python: Functions and Methods
Strings in Python are a crucial data type used to handle text. Python provides a rich set of built-in functions and methods to manipulate strings efficiently. This article covers these functions and methods in detail, offering examples and explanations to help you master string manipulation in Python.
String Basics
A string in Python is a sequence of characters enclosed within single quotes ('
), double quotes ("
), triple single quotes ('''
), or triple double quotes ("""
). Strings are immutable, meaning their contents cannot be changed after they are created.
single_quote_str = 'Hello, World!'
double_quote_str = "Hello, World!"
triple_single_quote_str = '''Hello,
World!'''
triple_double_quote_str = """Hello,
World!"""
String Functions
Python provides several built-in functions to perform operations on strings.
len()
Returns the length of a string.
text = "Hello, World!"
print(len(text)) # Outputs: 13
str()
Converts an object to a string.
num = 123
text = str(num)
print(text) # Outputs: '123'
ord()
Returns the Unicode code point for a given character.
char = 'A'
print(ord(char)) # Outputs: 65
chr()
Returns the character represented by a Unicode code point.
code = 65
print(chr(code)) # Outputs: 'A'
repr()
Returns a string containing a printable representation of an object.
value = 3.14
print(repr(value)) # Outputs: '3.14'
String Methods
Python’s string methods are functions that are called on string objects. They do not modify the original string but return a new string or value.
Case Conversion Methods
str.lower()
: Converts all characters in a string to lowercase.
text = "Hello, World!"
print(text.lower()) # Outputs: 'hello, world!'
str.upper()
: Converts all characters in a string to uppercase.
print(text.upper()) # Outputs: 'HELLO, WORLD!'
str.capitalize()
: Capitalizes the first character of the string.
print(text.capitalize()) # Outputs: 'Hello, world!'
str.title()
: Converts the first character of each word to uppercase.
print(text.title()) # Outputs: 'Hello, World!'
str.swapcase()
: Swaps the case of all characters in the string.
print(text.swapcase()) # Outputs: 'hELLO, wORLD!'
Searching and Replacing
str.find()
: Returns the lowest index of the substring if found, otherwise -1.
print(text.find('World')) # Outputs: 7
str.rfind()
: Returns the highest index of the substring if found, otherwise -1.
print(text.rfind('o')) # Outputs: 8
str.index()
: Similar tofind()
, but raises aValueError
if the substring is not found.
print(text.index('World')) # Outputs: 7
str.rindex()
: Similar torfind()
, but raises aValueError
if the substring is not found.
print(text.rindex('o')) # Outputs: 8
str.replace()
: Replaces occurrences of a substring with another substring.
print(text.replace('World', 'Python')) # Outputs: 'Hello, Python!'
Splitting and Joining
str.split()
: Splits the string into a list of substrings based on a delimiter.
print(text.split(', ')) # Outputs: ['Hello', 'World!']
str.rsplit()
: Splits the string from the right based on a delimiter.
print(text.rsplit(', ')) # Outputs: ['Hello', 'World!']
str.splitlines()
: Splits the string at line breaks.
multi_line_text = "Hello\nWorld!"
print(multi_line_text.splitlines()) # Outputs: ['Hello', 'World!']
str.join()
: Joins elements of an iterable into a single string with a specified separator.
words = ['Hello', 'World']
print(', '.join(words)) # Outputs: 'Hello, World'
Trimming and Padding
str.strip()
: Removes leading and trailing whitespace.
whitespace_text = " Hello, World! "
print(whitespace_text.strip()) # Outputs: 'Hello, World!'
str.lstrip()
: Removes leading whitespace.
print(whitespace_text.lstrip()) # Outputs: 'Hello, World! '
str.rstrip()
: Removes trailing whitespace.
print(whitespace_text.rstrip()) # Outputs: ' Hello, World!'
str.zfill()
: Pads the string on the left with zeros to fill a specified width.
num_str = "42"
print(num_str.zfill(5)) # Outputs: '00042'
Checking Content
str.startswith()
: Checks if the string starts with a specified substring.
print(text.startswith('Hello')) # Outputs: True
str.endswith()
: Checks if the string ends with a specified substring.
print(text.endswith('!')) # Outputs: True
str.isalpha()
: Checks if all characters in the string are alphabetic.
alpha_str = "HelloWorld"
print(alpha_str.isalpha()) # Outputs: True
str.isdigit()
: Checks if all characters in the string are digits.
digit_str = "12345"
print(digit_str.isdigit()) # Outputs: True
str.isalnum()
: Checks if all characters in the string are alphanumeric.
alnum_str = "Hello123"
print(alnum_str.isalnum()) # Outputs: True
str.isspace()
: Checks if all characters in the string are whitespace.
space_str = " "
print(space_str.isspace()) # Outputs: True
str.islower()
: Checks if all characters in the string are lowercase.
lower_str = "hello"
print(lower_str.islower()) # Outputs: True
str.isupper()
: Checks if all characters in the string are uppercase.
upper_str = "HELLO"
print(upper_str.isupper()) # Outputs: True
Formatting
str.format()
: Formats strings using placeholders.
name = "Alice"
age = 30
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str) # Outputs: 'My name is Alice and I am 30 years old.'
str.format_map()
: Formats strings using a dictionary.
info = {'name': 'Alice', 'age': 30}
formatted_str = "My name is {name} and I am {age} years old.".format_map(info)
print(formatted_str) # Outputs: 'My name is Alice and I am 30 years old.'
f-strings (formatted string literals)
: Introduced in Python 3.6, f-strings are a concise way to embed expressions inside string literals.
formatted_str = f"My name is {name} and I am {age} years old."
print(formatted_str) # Outputs: 'My name is Alice and I am 30 years old.'
Encoding and Decoding
str.encode()
: Encodes the string to bytes using the specified encoding.
encoded_str = text.encode('utf-8')
print(encoded_str) # Outputs: b'Hello, World!'
bytes.decode()
: Decodes bytes to a string using the specified encoding.
decoded_str = encoded_str.decode('utf-8')
print(decoded_str) # Outputs: 'Hello, World!'