Python String Methods
Introduction
In Python, strings are immutable objects, meaning once a string is created, it cannot be changed. However, Python provides a rich set of string methods to manipulate and work with text data efficiently.
str.upper()
Description: Returns a new string with all alphabetic characters converted to uppercase.
Example:
text = "hello world" result = text.upper() print(result) # Output: HELLO WORLD
str.lower()
Description: Returns a new string with all alphabetic characters converted to lowercase.
Example:
text = "HELLO WORLD" result = text.lower() print(result) # Output: hello world
str.title()
Description: Returns a new string where the first letter of each word is capitalized and all other letters are in lowercase.
Example:
text = "hello world" result = text.title() print(result) # Output: Hello World
str.capitalize()
Description: Returns a new string with the first character capitalized and all other characters in lowercase.
Example:
text = "hello world" result = text.capitalize() print(result) # Output: Hello world
str.strip()
Description: Returns a new string with leading and trailing whitespace removed.
Example:
text = " hello " result = text.strip() print(result) # Output: hello
str.lstrip()
Description: Returns a new string with leading whitespace removed.
Example:
text = " hello" result = text.lstrip() print(result) # Output: hello
str.rstrip()
Description: Returns a new string with trailing whitespace removed.
Example:
text = "hello " result = text.rstrip() print(result) # Output: hello
str.find(substring)
Description: Returns the lowest index in the string where the substring is found. Returns -1 if the substring is not found.
Example:
text = "hello world" index = text.find("world") print(index) # Output: 6
str.rfind(substring)
Description: Returns the highest index in the string where the substring is found. Returns -1 if the substring is not found.
Example:
text = "hello world world" index = text.rfind("world") print(index) # Output: 12
str.replace(old, new)
Description: Returns a new string with all occurrences of old replaced by new.
Example:
text = "hello world" result = text.replace("hello", "hi") print(result) # Output: hi world
str.split(separator)
Description: Splits the string into a list using the specified separator. The default separator is any whitespace.
Example:
text = "hello world" result = text.split() print(result) # Output: ['hello', 'world']
With a specific separator:
text = "hello,world" result = text.split(',') print(result) # Output: ['hello', 'world']
str.join(iterable)
Description: Joins the elements of the iterable into a single string with the string used as a separator.
Example:
elements = ["hello", "world"] result = " ".join(elements) print(result) # Output: hello world
str.startswith(prefix)
Description: Returns True if the string starts with the specified prefix, otherwise False.
Example:
text = "hello world" result = text.startswith("hello") print(result) # Output: True
str.endswith(suffix)
Description: Returns True if the string ends with the specified suffix, otherwise False.
Example:
text = "hello world" result = text.endswith("world") print(result) # Output: True
str.zfill(width)
Description: Returns a new string of the specified width with leading zeros added.
Example:
text = "42" result = text.zfill(5) print(result) # Output: 00042
str.isalpha()
Description: Returns True if all characters in the string are alphabetic, otherwise False.
Example:
text = "hello" result = text.isalpha() print(result) # Output: True
str.isdigit()
Description: Returns True if all characters in the string are digits, otherwise False.
Example:
text = "12345" result = text.isdigit() print(result) # Output: True
str.isspace()
Description: Returns True if all characters in the string are whitespace, otherwise False.
Example:
text = " " result = text.isspace() print(result) # Output: True
str.strip(chars)
Description: Removes specified characters from the beginning and end of the string.
Example:
text = "xxxhello xxx" result = text.strip("x") print(result) # Output: hello
str.format(*args, **kwargs)
Description: Allows inserting values into a string using {} as placeholders.
Example:
name = "Alice" age = 30 text = "Name: {}, Age: {}".format(name, age) print(text) # Output: Name: Alice, Age: 30
With named parameters:
text = "Name: {name}, Age: {age}".format(name="Alice", age=30) print(text) # Output: Name: Alice, Age: 30
str.rjust(width, fillchar)
Description: Returns a new string of the specified width with the original string right-justified and padded with the specified fill character.
Example:
text = "42" result = text.rjust(5, '0') print(result) # Output: 00042
str.ljust(width, fillchar)
Description: Returns a new string of the specified width with the original string left-justified and padded with the specified fill character.
Example:
text = "42" result = text.ljust(5, '0') print(result) # Output: 42000
str.center(width, fillchar)
Description: Returns a new string of the specified width with the original string centered and padded with the specified fill character.
Example:
text = "42" result = text.center(5, '0') print(result) # Output: 00420
str.partition(separator)
Description: Splits the string into a tuple (head, separator, tail) using the specified separator. Returns (string, ”, ”) if the separator is not found.
Example:
text = "hello world" result = text.partition("world") print(result) # Output: ('hello ', 'world', '')
str.rpartition(separator)
Description: Splits the string into a tuple (head, separator, tail) using the specified separator, starting from the end. Returns (”, ”, string) if the separator is not found.
Example:
text = "hello world world" result = text.rpartition("world") print(result) # Output: ('hello world ', 'world', '')
str.expandtabs(tabsize)
Description: Replaces tab characters in the string with spaces. tabsize specifies the number of spaces per tab.
Example:
text = "hello\tworld" result = text.expandtabs(4) print(result) # Output: hello world
str.islower()
Description: Returns True if all alphabetic characters in the string are lowercase, otherwise False.
Example:
text = "hello world" result = text.islower() print(result) # Output: True
str.isupper()
Description: Returns True if all alphabetic characters in the string are uppercase, otherwise False.
Example:
text = "HELLO WORLD" result = text.isupper() print(result) # Output: True
str.istitle()
Description: Returns True if each word in the string starts with an uppercase letter and the rest of the letters are lowercase.
Example:
text = "Hello World" result = text.istitle()
str.istitle() (continued)
Description: Returns True if each word in the string starts with an uppercase letter and the rest of the letters are lowercase. Returns False otherwise.
Example:
text = "Hello World" result = text.istitle() print(result) # Output: True
str.isnumeric()
Description: Returns True if all characters in the string are numeric characters. This includes digit characters as well as other numeric characters (e.g., superscript numbers).
Example:
text = "12345" result = text.isnumeric() print(result) # Output: True
str.isdecimal()
Description: Returns True if all characters in the string are decimal characters (digits). It does not include numeric characters that are not used in decimal notation.
Example:
text = "12345" result = text.isdecimal() print(result) # Output: True
str.isidentifier()
Description: Returns True if the string is a valid identifier in Python (i.e., it starts with a letter or underscore, and contains only letters, digits, and underscores).
Example:
text = "variable_name" result = text.isidentifier() print(result) # Output: True
str.isprintable()
Description: Returns True if all characters in the string are printable. This includes letters, digits, punctuation, and whitespace characters, but excludes control characters.
Example:
text = "hello world" result = text.isprintable() print(result) # Output: True
str.removeprefix(prefix)
Description: Returns a new string with the specified prefix removed if it is present. If the prefix is not found, returns the original string.
Example:
text = "TestHook" result = text.removeprefix("Test") print(result) # Output: Hook
str.removesuffix(suffix)
Description: Returns a new string with the specified suffix removed if it is present. If the suffix is not found, returns the original string.
Example:
text = "MiscTests.py" result = text.removesuffix(".py") print(result) # Output: MiscTests
str.encode(encoding=’utf-8′, errors=’strict’)
Description: Encodes the string into bytes using the specified encoding (default is ‘utf-8’). The errors argument specifies how encoding errors are handled (e.g., ‘strict’, ‘ignore’, ‘replace’).
Example:
text = "hello" result = text.encode('utf-8') print(result) # Output: b'hello'
str.decode(encoding=’utf-8′, errors=’strict’)
Description: Decodes bytes into a string using the specified encoding (default is ‘utf-8’). The errors argument specifies how decoding errors are handled (e.g., ‘strict’, ‘ignore’, ‘replace’).
Example:
text_bytes = b'hello' result = text_bytes.decode('utf-8') print(result) # Output: hello
Conclusion
This course has covered a wide range of string methods available in Python. These methods are essential for manipulating and analyzing text data effectively.
You can use these methods to:
- Transform Text: Convert to uppercase, lowercase, or title case.
- Manipulate Whitespace: Remove or trim spaces, and justify text.
- Search and Replace: Find substrings, replace content, and split strings.
- Check and Validate: Check for string properties like being numeric, alphabetic, or printable.
Feel free to experiment with these methods to deepen your understanding. If you have further questions or need clarification on any topic, don’t hesitate to ask!