DEV Community

Manisha Kundrapu
Manisha Kundrapu

Posted on

Python String Methods

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello123@"
print(string.isalnum()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello123"
print(string.isalpha()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "12345abc"
print(string.isdecimal()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "12345abc"
print(string.isdigit()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "123variable"
print(string.isidentifier()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello World"
print(string.islower()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "123abc"
print(string.isnumeric()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "\nHello World!"
print(string.isprintable()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = " Hello World "
print(string.isspace()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello, World!"
print(string.istitle()) # Output: True
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello World"
print(string.isupper()) # Output: False
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
words = ["1", "2", "3"]
separator = "-"
print(separator.join(words)) # Output: "1-2-3"
Enter fullscreen mode Exit fullscreen mode

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     "
Enter fullscreen mode Exit fullscreen mode
string = "Hello"
print(string.ljust(10, "-")) # Output: "Hello-----"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
string = "123"
print(string.lower()) # Output: "123"
Enter fullscreen mode Exit fullscreen mode

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  "
Enter fullscreen mode Exit fullscreen mode
string = "====Hello World==="
print(string.lstrip("=")) # Output: "Hello World==="
Enter fullscreen mode Exit fullscreen mode

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)) 
Enter fullscreen mode Exit fullscreen mode

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(",")) 
Enter fullscreen mode Exit fullscreen mode

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(",", "-")) 
Enter fullscreen mode Exit fullscreen mode

Output: "Hello- World!"

string = "Hello, World!"
print(string.replace(",", "-", 1)) 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello, World!"
print(string.rfind("x")) # Output: -1
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello, World!"
print(string.rindex("x")) 
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
string = "Hello"
print(string.rjust(10, "-")) # Output: "-----Hello"
Enter fullscreen mode Exit fullscreen mode

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(",")) 
Enter fullscreen mode Exit fullscreen mode

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)) 
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
string = "====Hello World==="
print(string.rstrip("=")) # Output: "====Hello World"
Enter fullscreen mode Exit fullscreen mode

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()) 
Enter fullscreen mode Exit fullscreen mode

Output: ["Hello", "World,", "How", "are", "you?"]

string = "Hello-World-How-are-you?"
print(string.split("-")) 
Enter fullscreen mode Exit fullscreen mode

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()) 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
string = "Hello, World!"
print(string.startswith("World", 7)) # Output: True
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
string = "====Hello World==="
print(string.strip("=")) # Output: "Hello World"
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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()) 
Enter fullscreen mode Exit fullscreen mode

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)) 
Enter fullscreen mode Exit fullscreen mode

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()) 
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
string = "-42"
print(string.zfill(5)) # Output: "-0042"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)