Python String Methods

We will explore the complete list of string methods available in Python. Python provides a rich set of built-in methods to manipulate and process strings. String in python is used to represent text-based data such as words, sentences, and paragraphs.

In Python, you can manipulate, combine, and process a string in a variety of ways. Strings are immutable in Python, which means you cannot change their content. However, when you modify a string it creates a new string in memory.

1. Python String Methods

Below is the complete list of string methods available in Python, along with a brief description of each method.

Python String MethodsDescription
str.split() Splits a string into a list of substrings.
str.upper() Converts the string to uppercase.
str.isdigit() Checks if the string consists of digits.
str.endswith() Returns True if the string ends with a substring.
str.replace() Replaces all occurrences of a substring.
str.isdecimal() Checks if a string is decimal characters only.
str.isnumeric() Returns True if all characters in the string are numeric characters.
str.find() Returns index of first substring occurrence.
str.rfind() Returns index of last substring occurrence.
str.index() Returns index of first substring occurrence. Raise Value error if not found.
str.rindex() Returns index of first substring occurrence. Raise Value error if not found.
str.capitalize() Capitalizes the first character of string.
str.casefold() Converts a string to lowercase form.
str.center()Centers string in specified width.
str.ljust() Left-justifies string in specified width.
str.rjust() Right-justifies string in specified width.
str.strip() Removes leading/trailing whitespaces from string.
str.lstrip()Removes leading whitespaces from string.
str.rstrip()Removes trailing whitespaces from string.
str.join() Joins a list of strings using the string as a separator.
str.encode() Encodes the string into a specified encoding format.
str.format() Inserts values into string placeholders.
str.format_map() Formats the specified values and inserts them inside the string’s placeholder using mapping.
str.maketrans() Returns a translation table usable for str.translate().
str.translate() Replaces specified characters in the string with the characters specified in the translation table.
str.count() Counts the number of substring occurrences in string.
str.startswith() Checks if the string starts with specified prefix.
str.expandtabs()Replaces tab characters in the string with spaces.
str.zfill() Fills string left with zeros to width.
str.isalnum() Returns True if a String is Number.
Complete list of string methods

1. split() – Split the String

The split() method returns a list of strings after breaking the original string by a specified separator or delimiter. If no separator is specified, the method returns a list of words split by whitespaces.

Syntax:


# Syntax
str.split(sep=None, maxsplit=-1)
  • sep is the specified separator or delimiter
  • maxsplit specifies the maximum number of splits to be made

Example:


# Example
text = "I Love SparkByExamples"
words = text.split()
print(words)

# Output
# ['I', 'Love', 'SparkByExamples']

2. upper() – Convert String to Uppercase

The upper() method is a built-in method in Python that allows you to convert all the characters in a string to uppercase. This method does not modify the original string but instead returns a new string with all characters in uppercase.

Syntax:


# Syntax
str.upper()

Example:


# Example
text_upper = text.upper()
print(text_upper)

# Output
# I LOVE SPARKBYEXAMPLES

3. capitalize() – Make String Capitalize

The str.capitalize() is a method in Python that takes a string and returns a copy of the string with the first character capitalized and the rest of the characters in lowercase.


# Example
capitalized_text = text.capitalize()
print(capitalized_text)

# Ouptut
# I love SparkByExamples

4. casefolde() – Make String Lowercase

In Python, str.casefold() is a string method that returns a string that has been case-folded. casefold means that the string has been converted to a form suitable for caseless matching.


# Example
text = "I LoVE spArKByExample"
lower_case = text.casefold()
print(lower_case)

# Output:
# i love sparkbyexample

5. count() – Find Frequency in a String

The count() method returns the number of times a specific substring occurs in a string.

Syntax:


# Syntax
str.count(substring, start, end)
  • substring : The string that we want to count in
  • start : It is the starting index ( Included)
  • end : it is the last index ( Excluded)

Example:


# Check a substring
word_count = text.count("Spark")
# Output : 1

# Check a character
count = text.count('S')
# Output : 1

# Check in a range
text.count("h", 2, 10)

6. startswith() – Check if String Starts with Substring

To Check if a String starts with a substring, you can use str.startswith. This method is used to check if a string starts with the specified prefix. As can be seen in the following Example, It returns a boolean value indicating whether the original string starts with the prefix.

Syntax:


# Syntax
str.startswith(prefix, start=0, end=len(string))

Parameters:

  • prefix: To be checked against the original string.
  • start (optional): Starting index. The default value is 0.
  • end (optional): Ending index. The default value is the length of the string.

# Example
print(text.startswith("i")) 
# Output: True
print(text.startswith("Love", 7)) 
# Output: False
print(text.startswith("Hi")) 
# Output: False

7. endswith() – String Ends with Substring

Similarly to the above method, str.endswith() method in Python is used to check if the string ends with the specified suffix or not. The Syntax is similar to the str.startswith(). Remember, these two methods are just the replacement of regular expressions.


# Checking if the string ends with "Examples"
result = string.endswith("Examples")
print("String ends with 'Examples': ", result)

8. isdigit() – Check if a String is a Digit

The str.isdigit() is a method that takes a string as an input and returns True if all the characters in the string are digits, and there is at least one character. If the string has characters other than digits or is empty, it returns False.


# Example
string = "12345"
result = string.isdigit()
print(result)
# Output: True

string = "12345a"
result = string.isdigit()
print(result)
# Output: False

9. replace() – Replace Characters in a String

The str.replace() method is used to replace all occurrences of a specified substring with another substring. Following is the Syntax of this method.

Syntax:


# Syntax
String.replace(oldvalue, newvalue, count)
  • oldvalue: Required. The value you want to replace
  • newvalue: Required. The value you want to replace the old value with
  • count: Optional. The number of times you want to replace the old value.

Example:


# Example
print(text.replace("SparkByExamples", "Java"))
# Output
# I Love Java

10. isdecimal() – Check if a String Digit is Decimal

The str.isdecimal() method returns a boolean value. If all characters in the string are decimal characters, the method returns True, otherwise it returns False.


# Example
text = "1234567890"
print(text.isdecimal()) 
# Output: True

text = "1234567890abc"
print(text.isdecimal()) 
# Output: False

11. isnumeric() – Check if a string is a numbers

This method is used to check if a string consists only of numbers. The str.isnumeric() returns True if indicating all characters in a string are numeric characters. A numeric character is a character for which the is_numeric property in Unicode is True.


# Example
string = "12345"
result = string.isnumeric()
print(result)  
# True

string = "1234.5"
result = string.isnumeric()
print(result)  
# False

12. find() – Find Index of Substring ( Safe)

The str.find() method returns the index of the first occurrence of a specified substring in the string. If the substring is not found, it returns -1. It is the replacement of the index() method. This method is more safe then using the index() method.

Syntax:


# Syntax
string.find(substring, start, end)

Example:


# Find the index of the first occurrence of the substring 'Love'
index = string.find('Love')

# Print the result
print(index)

13. rfind() – Index of last occurrence ( Safe)

The str.rfind() method returns the highest index of a substring in a given string, or -1 if the substring is not found. By the highest index we mean the last occurrence of the substring.


# Search for the last occurrence of 'Spark'
result = string.rfind("Spark")
print(result)
# Output: 12

14. index() – Find Index of a Substring

The str.index() method returns the index of the first occurrence of a specified substring in the string. If the substring is not found, it raises a ValueError. It is same is find() except it will raise the ValueError if there is no match.

Syntax:


# Syntax
str.index(sub[, start[, end]])
  • sub: Required, the substring to search for
  • start: Optional, an integer specifying the starting position for the search
  • end: Optional, an integer specifying the ending position for the search

Example:


# Example
index = sentence.index("Spark")
print(index)
# Output: 4

15. rindex() – Index of Last Occurrence

Just like the str.rfind(), we can use str.rindex() to returns the last index in the string where substring is found.


# Example
result = text.rindex("S")
print(result)
# Output: 14

16. ljust() – Left-justify String

This method is used to format and align string values to a specific width, often used in output formatting. It returns a left-justified string of a given width.


# Example
result = text.ljust(20, '*')
print("Left-justified text: ", result)
# Output 
# Left-justified text: SparkByExamples********

17. rjust() – Right-justify String

It works the same way to ljust(), except it fill the string with characters from the right side. The returned string is padded on the left with a specified fill character (default is space) until the desired width is reached.


# Example
print(text.rjust(20, '*'))
# Output
# *******SparkByExamples

18. strip() – Remove Whitespaces

str.strip() is a string method in Python that returns a copy of the string with leading and trailing white space characters removed. It takes an optional set of characters to remove as an argument. If no argument is passed, then white space characters such as spaces, tabs, and newlines are removed. Here’s an example:


# Example
text = "   i Love SparkByExamples  "
stripped_text = text.strip()
print("Stripped Text:", stripped_text)
# Output
# Stripped Text: i Love SparkByExamples

There are two other methods associated with this method. One is lstrip() and the other is rstrip(). Both of them can be used for the same purpose. if you want to remove only the left or right spaces you need to use them correspondingly.

19. join() – Concatenate List of Strings

The join() method is used to concatenate a list of strings with a specified separator string. It takes a list of strings as an argument and returns a string that is the concatenation of all the elements in the list, separated by the specified separator.


# Example
words = ['i', 'Love', 'SparkByExamples']
sentence = ' '.join(words)
print(sentence)
# Output
# i Love SparkByExamples

20. encode() – Encode a String

str.encode() is a method that is used to encode a string into a specific encoding format. This method returns a bytes object.

Syntax:


# Syntax
str.encode(encoding='utf-8', errors='strict')

Where,

  • encoding is the encoding format to encode the string. Default value is 'utf-8'
  • errors specifies the error handling scheme.

# Example
result = text.encode()
print(result) 
# b'i Love SparkByExamples'

21. center() – Padding String with Characters

The str.center() returns a centered string of length width. The original string is centered by padding the left and right sides with the specified fillchar (default is space), or truncating the string if it is too long.


# Example
result = text.center(30, "*")
print(result)
# Output
# ****i Love SparkbyExamples****

22. zfill() – Padding with Zeros

The str.zfill() is a method that returns a string of length width, where the original string is padded with zeros (0) on the left side to fill up to the desired width. The original string is not modified.


# Example
text = "123"
print(text.zfill(5))
# Output
# 00123

23. translate() – Replaced String with Character Mappings

The str.translate() returns a string where specified characters are replaced with their corresponding character mappings as defined in a translation table. The translation table is created using the str.maketrans() method.


# Example
translate_table = text.maketrans("S", "s")
s.translate(translate_table)
'I Love sparkByExamples'

24. maketrans() – Map Characters in String

The str.maketrans() method requires two ASCII string arguments of equal length, and returns a translation table that will map each character in the first argument to its corresponding character in the second argument. This table can be used besides str.translate() method.


# Example
x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
y = "abcdefghijklmnopqrstuvwxyz"
translation_table = str.maketrans(x, y)
"HELLO".translate(translation_table)
# Output : 'hello'

25. format_map() – Format String Using Mapping

It is similar to the str.format() method, but instead of passing positional or keyword arguments, a mapping or dictionary is passed to the method.

Syntax:


# Syntax
str.format_map(mapping)

Example:


# Example
person = {'first_name': 'Ali', 'last_name': 'H'}
greeting = "Hello, my name is {first_name} {last_name}."
print(greeting.format_map(person))
# Output
# Hello, my name is Ali H.

26. format() – Format String

It allows you to format a string by replacing placeholders in the string with values. The placeholders are indicated by curly braces {}.


# Example
site= "SparkByExamples"
time= 5

# Create a formatted string
formatted_string = "I visit {} for {} hours.".format(site, time)
print(formatted_string) 
# Output: 'I visit SparkByExamples for 5 hours.'

27. isalnum() – Check if String is Alphanumeric

This method returns True if all characters in a given string are alphanumeric (i.e., either alphabets or numbers), and there is at least one character in the string. It returns False otherwise.


# Example
text = "Python123"
print(text.isalnum())  
# True

text = "Python 123"
print(text.isalnum())  
# False

28. expandtabs() – Replace Tab Characters

The str.expandtabs() replaces tab characters (\t) in a string with spaces, and returns the expanded string. The number of spaces used per tab character can be specified as an argument.

Syntax:


# Syntax
string.expandtabs(tabsize=8)

Example:


# Example
text = "1\t2\t3"
result = text.expandtabs()
print(result) 
# "1       2       3"

Summary and Conclusion

We discussed Python String methods with examples. You have learned about the use of each python string method with examples. You now have a clear understanding of working with string methods in Python. Comment below if you have any questions.

Happy Learning!!!

AlixaProDev

I am an astute software engineer with extensive 3+ years of experience in developing full-stack web applications. My skillets include building backend services for different databases. Mainly I work with Python, Flask, Django, and FastAPIs. Being Python Specialist, I have worked with Numpy, Pandas, and other Python Libraries to build tools that make ETL normalization easier.

Leave a Reply