We already learned Python data types basics.
In this module, we will learn advanced methods of the data types.
Here we will learn only string as it has a lot of methods and other data types in Python Data Types Advanced - 2
String Advanced Methods
1. capitalize()
This method returns a copy of the string with its first character capitalized and the rest of the characters in lowercase.
Example
text = "hello world"
capitalized_text = text.capitalize()
print(capitalized_text) # Output: "Hello world"
2. count()
The count()
method returns the number of non-overlapping occurrences of a substring in the given string.
Example:
text = "python is powerful, python is versatile"
count = text.count("python")
print(count) # Output: 2
3. endswith()
This method checks if the string ends with a specified suffix and returns True
or False
.
Example:
text = "Hello, World!"
result = text.endswith("World!")
print(result) # Output: True
4. join(iterable)
:
The join()
method concatenates the elements of an iterable (e.g., a list or tuple) into a single string, using the string on which it's called as the separator.
Example:
words = ["Hello", "World", "Python"]
joined_text = " ".join(words)
print(joined_text) # Output: "Hello World Python"
In this example, the elements of the words
list are joined together with a space separator.
5. expandtabs()
The expandtabs()
method returns a copy of the string with tab characters ('\t'
) expanded to spaces. You can specify the tab size as an argument (default is 8 spaces).
Example:
text = "Python\tis\tawesome"
expanded_text = text.expandtabs(4)
print(expanded_text)
# Output: "Python is awesome"
6. find()
The find()
method searches for a substring in the given string and returns the lowest index where the substring is found. If the substring is not found, it returns -1
.
Example:
text = "Python is powerful, Python is versatile"
index = text.find("Python")
print(index) # Output: 0
7. format()
The format()
method is used for string formatting. It replaces placeholders in a string with values from specified arguments.
Example:
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
# Output: "My name is Alice and I am 30 years old."
8. format_map()
Similar to format()
, the format_map()
method is used for string formatting. It replaces placeholders in a string with values from a specified dictionary.
Example:
person_info = {"name": "Bob", "age": 25}
message = "My name is {name} and I am {age} years old.".format_map(person_info)
print(message)
# Output: "My name is Bob and I am 25 years old."
9. index()
The index()
method is similar to find()
, but it raises a ValueError
if the substring is not found, instead of returning -1
.
Example:
text = "Python is powerful, Python is versatile"
index = text.index("Python")
print(index) # Output: 0
# If substring is not found:
try:
index = text.index("Java")
except ValueError as e:
print("Substring not found:", e)
# Output: Substring not found: substring not found
10. isalnum()
The isalnum()
method checks if all characters in the string are alphanumeric (letters or numbers) and returns True
if they are, otherwise False
.
Example:
text = "Python3"
is_alphanumeric = text.isalnum()
print(is_alphanumeric) # Output: True
11. isalpha()
The isalpha()
method checks if all characters in the string are alphabetic (letters) and returns True
if they are, otherwise False
.
Example:
text = "Python"
is_alpha = text.isalpha()
print(is_alpha) # Output: True
12. isascii()
The isascii()
method checks if all characters in the string are ASCII characters (characters with ASCII values between 0 and 127) and returns True
if they are, otherwise False
.
Example:
text = "Python"
is_ascii = text.isascii()
print(is_ascii) # Output: True
13. isdecimal()
The isdecimal()
method checks if all characters in the string are decimal digits and returns True
if they are, otherwise False
.
Example:
text = "12345"
is_decimal = text.isdecimal()
print(is_decimal) # Output: True
14. isdigit()
The isdigit()
method checks if all characters in the string are digits (including digits from other scripts) and returns True
if they are, otherwise False
.
Example:
text = "12345"
is_digit = text.isdigit()
print(is_digit) # Output: True
15. isidentifier()
The isidentifier()
method checks if the string is a valid Python identifier (e.g., a variable name) and returns True
if it is, otherwise False
.
Example:
identifier = "my_variable"
is_valid_identifier = identifier.isidentifier()
print(is_valid_identifier) # Output: True
16. islower()
The islower()
method checks if all alphabetic characters in the string are lowercase and returns True
if they are, otherwise False
.
Example:
text = "python"
is_lower = text.islower()
print(is_lower) # Output: True
17. isnumeric()
The isnumeric()
method checks if all characters in the string are numeric characters and returns True
if they are, otherwise False
.
Example:
text = "12345"
is_numeric = text.isnumeric()
print(is_numeric) # Output: True
18. isprintable()
The isprintable()
method checks if all characters in the string are printable (can be displayed) and returns True
if they are, otherwise False
.
Example:
text = "Hello\nWorld"
is_printable = text.isprintable()
print(is_printable) # Output: False
19. isspace()
The isspace()
method checks if all characters in the string are whitespace characters (e.g., spaces, tabs, newlines) and returns True
if they are, otherwise False
.
Example:
text = " \t \n"
is_space = text.isspace()
print(is_space) # Output: True
20. istitle()
The istitle()
method checks if the string is in title case (the first character of each word is uppercase and the rest are lowercase) and returns True
if it is, otherwise False
.
Example:
text = "This Is Title Case"
is_title = text.istitle()
print(is_title) # Output: True
21. isupper()
The isupper()
method checks if all alphabetic characters in the string are uppercase and returns True
if they are, otherwise False
.
Example:
text = "PYTHON"
is_upper = text.isupper()
print(is_upper) # Output: True
22. lower()
The lower()
method returns a copy of the string with all alphabetic characters converted to lowercase.
Example:
text = "Hello World"
lower_text = text.lower()
print(lower_text) # Output: "hello world"
23. lstrip()
The lstrip()
method returns a copy of the string with leading (left) whitespace characters removed.
Example:
text = " Hello World "
stripped_text = text.lstrip()
print(stripped_text) # Output: "Hello World "
24. removeprefix(prefix)
The removeprefix()
method removes the specified prefix from the string if it exists. If the prefix is not found, the original string is returned.
Example:
text = "Prefix_Text"
new_text = text.removeprefix("Prefix_")
print(new_text) # Output: "Text"
25. removesuffix(suffix)
The removesuffix()
method removes the specified suffix from the string if it exists. If the suffix is not found, the original string is returned.
Example:
text = "Text_Suffix"
new_text = text.removesuffix("_Suffix")
print(new_text) # Output: "Text"
26. replace(old, new[, count])
The replace()
method replaces all occurrences of the old
substring with the new
substring. You can also specify an optional count
parameter to limit the number of replacements.
Example:
text = "Hello, World, Hello"
new_text = text.replace("Hello", "Hi")
print(new_text) # Output: "Hi, World, Hi"
27. rfind(sub[, start[, end]])
The rfind()
method searches for a substring in the given string from the right (end) and returns the highest index where the substring is found. If the substring is not found, it returns -1
.
Example:
text = "Python is powerful, Python is versatile"
index = text.rfind("Python")
print(index) # Output: 18
28. rindex(sub[, start[, end]])
The rindex()
method is similar to rfind()
, but it raises a ValueError
if the substring is not found, instead of returning -1
.
Example:
text = "Python is powerful, Python is versatile"
index = text.rindex("Python")
print(index) # Output: 18
# If substring is not found:
try:
index = text.rindex("Java")
except ValueError as e:
print("Substring not found:", e)
# Output: Substring not found: substring not found
29. rsplit([sep[, maxsplit]])
The rsplit()
method splits the string into a list of substrings from the right (end) based on the specified separator sep
. You can also specify an optional maxsplit
parameter to limit the number of splits.
Example:
text = "apple, banana, cherry, date"
words = text.rsplit(", ")
print(words) # Output: ['apple', 'banana', 'cherry', 'date']
30. rstrip([chars])
The rstrip()
method returns a copy of the string with trailing (right) characters removed. You can specify the characters to remove using the optional chars
parameter.
Example:
text = " Hello World "
stripped_text = text.rstrip()
print(stripped_text) # Output: " Hello World"
31. split([sep[, maxsplit]])
The split()
method splits the string into a list of substrings based on the specified separator sep
. You can also specify an optional maxsplit
parameter to limit the number of splits.
Example:
text = "apple, banana, cherry, date"
words = text.split(", ")
print(words) # Output: ['apple', 'banana', 'cherry', 'date']
32. splitlines([keepends])
The splitlines()
method splits the string at line breaks ('\n'
) and returns a list of lines. You can specify an optional keepends
parameter to include line break characters in the result.
Example:
text = "Line 1\nLine 2\nLine 3"
lines = text.splitlines()
print(lines) # Output: ['Line 1', 'Line 2', 'Line 3']
33. startswith(prefix[, start[, end]])
The startswith()
method checks if the string starts with the specified prefix
and returns True
if it does, otherwise False
.
Example:
text = "Hello, World!"
result = text.startswith("Hello")
print(result) # Output: True
34. strip([chars])
The strip()
method returns a copy of the string with leading and trailing characters removed. You can specify the characters to remove using the optional chars
parameter.
Example:
text = " Hello World "
stripped_text = text.strip()
print(stripped_text) # Output: "Hello World"
35. title()
The title()
method returns a copy of the string with the first character of each word capitalized and the rest of the characters in lowercase, making it title case.
Example:
text = "hello world"
title_text = text.title()
print(title_text) # Output: "Hello World"
36. upper()
The upper()
method returns a copy of the string with all alphabetic characters converted to uppercase.
Example:
text = "Hello World"
upper_text = text.upper()
print(upper_text) # Output: "HELLO WORLD"
37. zfill(width)
The zfill()
method pads the string with zeros (0) on the left side to make it a specified width. It's often used for formatting numbers.
Example:
number = "42"
padded_number = number.zfill(5)
print(padded_number) # Output: "00042"
These advanced string methods allow you to manipulate and format strings in various ways, making them powerful tools for working with textual data in Python.