Python provides a wide range of methods that can be applied on string objects.
Here are most of the string methods available in Python:
1. capitalize():
The capitalize() method converts the first character of a string to an uppercase letter and all other alphabets to lowercase.
Syntax : string.capitalize()
Example:
string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)
Output:
Hello world
2. casefold():
The casefold() method converts all characters of the string into lowercase letters and returns a new string.
Syntax : str.casefold()
Example:
string = "HELLO WORLD"
casefolded_string = string.casefold()
print(casefolded_string)
Output:
hello world
3. center():
The center() method returns a new centered string after padding it with the specified character.
Syntax : str.center(width, [fillchar])
width - length of the string with padded characters
fillchar (optional) - padding character
Example:
string = "hello"
centered_string = string.center(10, "-")
print(centered_string)
Output:
--hello---
4. count():
This method returns the number of non-overlapping occurrences of a substring in the string. You can also specify the start and end positions to search within the string.
Syntax : string.count(substring, start=..., end=...)
substring - string whose count is to be found.
start (Optional) - starting index within the string where search starts.
end (Optional) - ending index within the string where search ends.
Example:
string = "hello world"
count = string.count("o")
print(count)
Output:
2
5. encode():
This method returns an encoded version of the string using the specified encoding.
Syntax : encode(encoding="utf-8", errors="strict")
By default, the encode() method doesn't require any parameters.
It returns an utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.
However, it takes two parameters:
encoding : the encoding type a string has to be encoded to.
errors : response when encoding fails.
There are six types of error response.
strict - default response which raises a UnicodeDecodeError exception on failure.
ignore - ignores the unencodable unicode from the result.
replace - replaces the unencodable unicode to a question mark.
xmlcharrefreplace - inserts XML character reference instead of unencodable unicode.
backslashreplace - inserts a \uNNNN escape sequence instead of unencodable unicode.
namereplace - inserts a \N{...} escape sequence instead of unencodable unicode.
Example:
string = "hello world"
encoded_string = string.encode("utf-8")
print(encoded_string)
Output:
b'hello world'
6. endswith():
This method returns True if the string ends with the specified suffix. You can also specify the start and end positions to search within the string.
Syntax : endswith(suffix[, start[, end]])
Example:
string = "hello world"
ends_with = string.endswith("ld")
print(ends_with)
Output:
True
7. expandtabs():
The expandtabs() method returns a copy of string with all tab characters '\t' replaced with whitespace characters until the next multiple of tabsize parameter.
Syntax : string.expandtabs(tabsize)
The expandtabs() takes an integer tabsize argument. The default tabsize is 8.
Example:
string = "hello\tworld"
expanded_string = string.expandtabs(4)
print(expanded_string)
Output:
hello world
8. find():
This method returns the lowest index of the first occurrence of a substring in the string.
If the substring is not found, it returns -1.
You can also specify the start and end positions to search within the string.
Syntax : find(sub[, start[, end]])
sub - It is the substring to be searched in the str string.
start and end (optional) - The range str[start:end] within which substring is searched.
Example:
string = "hello world"
index = string.find("o")
print(index)
Output:
4
9. format() :
This method formats the string using the specified arguments.
Syntax : format(*args, **kwargs)
Example:
name = "Alice"
age = 30
formatted_string = "My name is {0} and I am {1} years old".format(name, age)
print(formatted_string)
Output:
My name is Alice and I am 30 years old
10. format_map():
This method formats the string using the specified mapping.
Syntax : str.format_map(mapping)
Example:
mapping = {"name": "Alice", "age": 30}
formatted_string = "My name is {name} and I am {age} years old".format_map(mapping)
print(formatted_string)
Output:
My name is Alice and I am 30 years old
11. index():
The index() method returns the index of the first occurrence of a substring in a string. If the substring is not found, it raises a ValueError.
Syntax : string.index(substring[, start[, end]])
Example:
string = "Hello World"
print(string.index("o")) # Output: 4
print(string.index("ld")) # Output: 9
12. isalnum():
The isalnum() method returns True if all the characters in the string are alphanumeric (letters or numbers), and there is at least one character. Otherwise, it returns False.
Syntax : string.isalnum()
Example:
string = "Hello123"
print(string.isalnum()) # Output: True
string = "Hello123@"
print(string.isalnum()) # Output: False
13. isalpha():
The isalpha() method returns True if all the characters in the string are alphabets (letters), and there is at least one character. Otherwise, it returns False.
Syntax : string.isalpha()
Example:
string = "Hello"
print(string.isalpha()) # Output: True
string = "Hello123"
print(string.isalpha()) # Output: False
14. isdecimal():
The isdecimal() method returns True if all the characters in the string are decimal (numbers), and there is at least one character. Otherwise, it returns False.
Syntax : string.isdecimal()
Example:
string = "12345"
print(string.isdecimal()) # Output: True
string = "12345abc"
print(string.isdecimal()) # Output: False
15. isdigit():
The isdigit() method returns True if all the characters in the string are digits (0-9), and there is at least one character. Otherwise, it returns False.
Syntax : string.isdigit()
Example:
string = "12345"
print(string.isdigit()) # Output: True
string = "12345abc"
print(string.isdigit()) # Output: False
16. isidentifier():
The isidentifier() method returns True if the string is a valid Python identifier. A valid identifier is a sequence of letters, digits, or underscore characters that starts with a letter or an underscore.
Syntax : string.isidentifier()
Example:
string = "my_variable"
print(string.isidentifier()) # Output: True
string = "123variable"
print(string.isidentifier()) # Output: False
17. islower():
The islower() method returns True if all the alphabetic characters in the string are lowercase. Otherwise, it returns False.
Syntax : string.islower()
Example:
string = "hello world"
print(string.islower()) # Output: True
string = "Hello World"
print(string.islower()) # Output: False
18. isnumeric():
The isnumeric() method returns True if all the characters in the string are numeric characters. Otherwise, it returns False.
Syntax : string.isnumeric()
Example:
string = "123"
print(string.isnumeric()) # Output: True
string = "123abc"
print(string.isnumeric()) # Output: False
19. isprintable():
The isprintable() method returns True if all the characters in the string are printable or the string is empty. Otherwise, it returns False. A character is considered printable if it is not a control character.
Syntax : string.isprintable()
Example:
string = "Hello World!"
print(string.isprintable()) # Output: True
string = "\nHello World!"
print(string.isprintable()) # Output: False
20. isspace():
The isspace() method returns True if all the characters in the string are whitespace characters. Otherwise, it returns False. A whitespace character is a space, tab, newline, or any other character that is considered a space.
Syntax : string.isspace()
Example:
string = " \t\n"
print(string.isspace()) # Output: True
string = " Hello World "
print(string.isspace()) # Output: False
21. istitle():
The istitle() method returns True if the string is a titlecased string, i.e., the first character of each word in the string is in uppercase and all other characters are in lowercase. Otherwise, it returns False.
Syntax : string.istitle()
Example:
string = "Hello World"
print(string.istitle()) # Output: False
string = "Hello, World!"
print(string.istitle()) # Output: True
22. isupper():
The isupper() method returns True if all the alphabetic characters in the string are uppercase. Otherwise, it returns False.
Syntax: string.isupper()
Example:
string = "HELLO WORLD"
print(string.isupper()) # Output: True
string = "Hello World"
print(string.isupper()) # Output: False
23. join():
The join() method concatenates a list of strings using the specified string as the separator. It returns a new string that is the concatenation of all the strings in the list, separated by the specified string.
Syntax : separator.join(iterable)
Example:
words = ["Hello", "World"]
separator = ", "
print(separator.join(words)) # Output: "Hello, World"
words = ["1", "2", "3"]
separator = "-"
print(separator.join(words)) # Output: "1-2-3"
24. ljust():
The ljust() method returns a left-justified version of the string. It pads the original string with a specified character (by default, a space character) on the right side until the resulting string reaches the specified length.
Syntax : string.ljust(width[, fillchar])
Example:
string = "Hello"
print(string.ljust(10)) # Output: "Hello "
string = "Hello"
print(string.ljust(10, "-")) # Output: "Hello-----"
25. lower():
The lower() method returns a new string with all the alphabetic characters in the original string converted to lowercase.
Syntax : string.lower()
Example:
string = "Hello World"
print(string.lower()) # Output: "hello world"
string = "123"
print(string.lower()) # Output: "123"
26. lstrip():
The lstrip() method returns a new string with all leading whitespace characters removed. By default, it removes all whitespace characters, but you can also specify a specific set of characters to remove.
Syntax : string.lstrip([chars])
Example:
string = " Hello World "
print(string.lstrip()) # Output: "Hello World "
string = "====Hello World==="
print(string.lstrip("=")) # Output: "Hello World==="
27. maketrans():
The maketrans() method creates a translation table that can be used with the translate() method to replace characters in a string.
Syntax : str.maketrans(x[, y[, z]])
Example:
intab = "aeiou"
outtab = "12345"
translation_table = str.maketrans(intab, outtab)
string = "Hello World"
print(string.translate(translation_table))
Output:
"H2ll4 W4rld"
28. partition():
The partition() method separates a string into three parts based on the first occurrence of a specified separator. It returns a tuple containing the left part of the string, the separator itself, and the right part of the string.
Syntax : string.partition(separator)
Example:
string = "Hello, World!"
print(string.partition(","))
Output:
("Hello", ",", " World!")
29. replace():
The replace() method returns a new string with all occurrences of a specified substring replaced with another substring.
Syntax : string.replace(old, new[, count])
Example:
string = "Hello, World!"
print(string.replace(",", "-"))
Output: "Hello- World!"
string = "Hello, World!"
print(string.replace(",", "-", 1))
Output: "Hello- World!"
30. rfind():
The rfind() method searches a string for a specified substring starting from the end of the string and returns the index of the last occurrence of the substring. If the substring is not found, it returns -1.
Syntax : string.rfind(sub[, start[, end]])
Example :
string = "Hello, World!"
print(string.rfind("l")) # Output: 10
string = "Hello, World!"
print(string.rfind("x")) # Output: -1
31. rindex():
The rindex() method is similar to the index() method, but it searches for a substring starting from the end of the string instead of the beginning. It raises a ValueError if the substring is not found.
Syntax : string.rindex(sub[, start[, end]])
Example:
string = "Hello, World!"
print(string.rindex("o")) # Output: 8
string = "Hello, World!"
print(string.rindex("x"))
Output:
ValueError: substring not found
32. rjust():
The rjust() method returns a right-justified version of the string. It pads the original string with a specified character (by default, a space character) on the left side until the resulting string reaches the specified length.
Syntax : string.rjust(width[, fillchar])
Example:
string = "Hello"
print(string.rjust(10)) # Output: " Hello"
string = "Hello"
print(string.rjust(10, "-")) # Output: "-----Hello"
33. rpartition():
The rpartition() method is similar to the partition() method, but it searches for a separator starting from the end of the string instead of the beginning.
Syntax : string.rpartition(separator)
Example:
string = "Hello, World!"
print(string.rpartition(","))
Output:
("Hello, World", ",", "")
34. rsplit():
The rsplit() method is similar to the split() method, but it splits the string from the right end instead of the left. You can also specify the maximum number of splits to perform.
Syntax: string.rsplit([sep[, maxsplit]])
Example:
string = "Hello World, How are you?"
print(string.rsplit(",", 1))
Output:
["Hello World", " How are you?"]
35. rstrip():
The rstrip() method returns a new string with all trailing whitespace characters removed. By default, it removes all whitespace characters, but you can also specify a specific set of characters to remove.
Syntax : string.rstrip([chars])
Example:
string = " Hello World "
print(string.rstrip()) # Output: " Hello World"
string = "====Hello World==="
print(string.rstrip("=")) # Output: "====Hello World"
36. split():
The split() method splits a string into a list of substrings based on a specified separator. By default, it splits the string on whitespace characters, but you can also specify a different separator.
Syntax : string.split([sep[, maxsplit]])
Example:
string = "Hello World, How are you?"
print(string.split())
Output: ["Hello", "World,", "How", "are", "you?"]
string = "Hello-World-How-are-you?"
print(string.split("-"))
Output: ["Hello", "World", "How", "are", "you?"]
37. splitlines():
The splitlines() method splits a string into a list of substrings based on newline characters. It works on both Windows and Unix-style newline characters.
Syntax : string.splitlines([keepends])
Example:
string = "Hello\nWorld\nHow\nare\nyou?"
print(string.splitlines())
Output:
["Hello", "World", "How", "are", "you?"]
38. startswith():
The startswith() method returns True if a string starts with a specified substring; otherwise, it returns False.
Syntax : string.startswith(substring[, start[, end]])
Example:
string = "Hello, World!"
print(string.startswith("Hello")) # Output: True
string = "Hello, World!"
print(string.startswith("World", 7)) # Output: True
39. strip():
The strip() method returns a new string with all leading and trailing whitespace characters removed. By default, it removes all whitespace characters, but you can also specify a specific set of characters to remove.
Syntax : string.strip([chars])
Example:
string = " Hello World "
print(string.strip()) # Output: "Hello World"
string = "====Hello World==="
print(string.strip("=")) # Output: "Hello World"
40. swapcase():
The swapcase() method returns a new string with all uppercase characters converted to lowercase and all lowercase characters converted to uppercase.
Syntax : string.swapcase()
Example:
string = "Hello, World!"
print(string.swapcase())
Output:
"hELLO, wORLD!"
41. title():
The title() method returns a new string with the first character of each word in the string capitalized and the remaining characters in lowercase.
Syntax : string.title()
Example:
string = "hello world"
print(string.title())
Output:
"Hello World"
42. translate():
The translate() method returns a new string where some specified characters are replaced with the character described in a dictionary, or in a mapping table.
Syntax : string.translate(table)
Example:
string = "Hello, World!"
translation_table = str.maketrans("o", "e")
print(string.translate(translation_table))
Output:
"Helle, Werld!"
43. upper():
The upper() method returns a new string with all the characters in uppercase.
Syntax : string.upper()
Example:
string = "Hello, World!"
print(string.upper())
Output:
"HELLO, WORLD!"
44. zfill():
The zfill() method pads a numeric string with zeros on the left side to fill a specified width. It does not modify the original string.
Syntax : string.zfill(width)
Example:
string = "42"
print(string.zfill(5)) # Output: "00042"
string = "-42"
print(string.zfill(5)) # Output: "-0042"
Top comments (0)