Python

10 most useful Python String Methods

The string data is the characters of an array that contains one or more characters as value for any programming language. All printable characters such as alphabets, numbers, special characters, etc. are commonly used in the string data. ASCII code and Unicode are mainly used for converting any character to a number that the computer can understand. Python uses Unicode characters for string data. We need to perform different types of tasks based on the programming purpose on the string data such as searching the particular character or characters, capitalizing the first character, making all characters uppercase, etc. Python has many built-in string methods to do these types of tasks very easily. The 10 most useful python string methods are explained in this article.

Use of format() method

format() method is an essential method of python to generate formatted output. It has many uses and it can be applied on both string and numeric data to generate formatted output. How this method can be used for index-based formatting of string data is shown in the following example.

Syntax:

{}.format(value)

The string and the placeholder position is defined inside the curly brackets ({}). It returns the formatted string based on the string and the values passed on the placeholder position.

Example:

The four types of formatting are shown in the following script. In the first output, index value {0} is used. No position is assigned in the second output. Two sequential positions are assigned in the third output. Three unordered positions are defined in the fourth output.

#!/usr/bin/env python3
# Apply single index with value
print("Learn {0} programming".format("Python"))

# Apply formatting without index value
print("Both {} and {} are scripting languages".format("Bash", "Python"))

# Apply multiple index with index value
print("\nStudent ID: {0}\nStudent Nmae: {1}\n".format("011177373", "Meher Afroz"))

# Apply multiple index without any order
print("{2} is a student of {0} department and he is studying in {1} semester".format("CSE",
"10","Farhan Akter"))

Output:

Use of split() method

This method is used to divide any string data based on any particular separator or delimiter. It can take two arguments and both are optional.

Syntax:

split([separator, [maxsplit]])

If this method is used without any argument then space will be used as a separator by default. Any character or a list of characters can be used as a separator. The second optional argument is used to define the limit of splitting the string. It returns a list of string.

Example:

The following script shows the uses of the split() method without any argument, with one argument, and with two arguments. Space is used to split the string when no argument is used. Next, the colon(:) is used as a separator argument. The comma(,) is used as a separator and 2 is used as the number of the split in the last split statement.

#!/usr/bin/env python3
# Define the first string value
strVal1 = "Python is very popular programming language now"
# Split the string based on space
splitList1 = strVal1.split()

# Define the second string value
strVal2 = "Python : PERL : PHP : Bash : Java"
# Split the string based on ':'
splitList2 = strVal2.split(':')

# Define the third string value
strVal3 = "Name:Fiaz Ahmed, Batch:34, Semester:10, Dept:CSE"
# Split the string based on ',' and divide the string into three parts
splitList3 = strVal3.split(',',2)

print("The output of first split:\n", splitList1)
print("The output of second split:\n", splitList2)
print("The output of third split:\n", splitList3)

Output:

Use of find() method

find() method is used to search the position of a particular string in the main string and return the position if the string exists in the main string.

Syntax:

find(searchText, [starting_position, [ ending_position]])

This method can take three arguments where the first argument is mandatory and the other two arguments are optional. The first argument contains the string value that will be searched, the second argument defines the starting position of the search and the third argument defines the ending position of the search. It returns the position of the searchText if it exists in the main string, otherwise, it returns -1.

Example:

The uses of find() method with one argument, two arguments, and third arguments are shown in the following script. The first output will be -1 because the searching text is ‘python’ and the variable, str contains the string, ‘Python’. The second output will return a valid position because the word, ‘program’ exists in str after the position10. The third output will return a valid position because the word, ‘earn’ exists within 0 to 5 position of the str.

#!/usr/bin/env python3
# define a string data
str = 'Learn Python programming'
# Search the position of the word 'python' from the starting
print(str.find('python'))  

# Search the string 'program' from the position 10
print(str.find('program', 10))

# Search the word 'earn' from 0 position and within next 5 characters  
print(str.find('earn', 0, 5))

Output:

Use of replace() method

replace() method is used to replace any particular portion of a string data by another string if the match found. It can take three arguments. Two arguments are mandatory and one argument is optional.

Syntax:

string.replace(search_string, replace_string [,counter])

The first argument takes the search string that you want to replace and the second argument takes the replace string. The third optional argument sets the limit for replacing string.

Example:

In the following script, the first replace is used to replace the word, ‘PHP’ by the word, ‘Java’ in the content of the str. The searching word exists in the str, so the word, ‘PHP’ will be replaced by the word, ‘Java‘. The third argument of the replace method is used in the next replace method and it will replace only the first match of the searching word.

#!/usr/bin/env python3
# Define a string data
str = "I like PHP but I like Python more"

# Replace a particular string of the string data if found
replace_str1 = str.replace("PHP", "Java")
# Print the original string and the replaced string
print("Original string:", str)
print("Replaced string:", replace_str1)

# Replace a particular string of the string data for the first match
replace_str2 = str.replace("like", "dislike",1)
print("\nOriginal string:",str)
print("Replaced string:",replace_str2)

Output:

Use of join() method

join() method is used to create a new string by combining other string with string, list of strings, or tuple of strings data.

Syntax:

separator.join(iterable)

It has only one argument that can be string, list, or tuple and the separator contains the string value that will be used for the concatenation.

Example:

The following script shows the uses of join() method for the string, list of the string, and the tuple of the strings. ‘,’ is used as a separator for the string, space is used as a separator for the list, and ‘:’ is used as a separator for the tuple.

#!/usr/bin/env python3

# Apply join on string data
print('Joining each character with comma:', ','.join('linuxhint'))
# Apply join on list of strings
print('Joining list of strings with space:', ' '.join(['I','like', 'programming']))
# Apply join on tuple of strings
print('Joining tuple of strings with colon:', ':'.join(('011156432','Mehnaz', '10','45')))

Output:

Use of strip() method

strip() method is used to remove white spaces from both sides of a string. There are two related methods for removing white spaces. lstrip() method to remove the white space from the left side and rstrip() method to remove the white space from the right side of the string. This method does not take any argument.

Syntax:

string.strip()

Example:

The following script shows the use of strip() method for a string value that contains many white spaces before and after the string. The extra text is added with the output of the strip() method to show how this method works.

#!/usr/bin/env python3

# Define a string data with space
strVal = "      Welcome to LinuxHint     "

# Print output before and after strip
print("The output before strip():", strVal)
print("The output after strip():", strVal.strip(),"(Added to check)")

Output:

Use of capitalize() method

capitalize() method is used to capitalize the first character of the string data and make the remaining characters to lower case.

Syntax:

string.capitalize()

This method does not take any argument. It returns the string after making the first character to uppercase and the remaining characters to lowercase.

Example:

In the following script, a string variable is defined with the mix of uppercase and lowercase characters. The capitalize() method will convert the first character of the string into a capital letter and the remaining characters to small letters.

#!/usr/bin/env python3

# Define the string
strVal = 'jubair Hosain IS a VeRy GooD programmer.'

# Apply capitalize() method
print(strVal.capitalize())

Output:

Use of count() method

count() method is used to count how many times a particular string appears in a text.

Syntax:

string.count(search_text [,  start [, end]])

This method has three arguments. The first argument is mandatory and the other two arguments are optional. The first argument contains the value that requires to search in the text. The second argument contains the start position of the search and the third argument contains the end position of the search.

Example:

The following script shows the three different uses of count() method. The first count() method will search the word, ‘is’ in the variable, strVal.  The second count() method searches the same word from position 20. The third count() method searches the same word within the position 50 to 100.

#!/usr/bin/env python3

# Define a long text with repeating words
strVal = 'Python is a powerful programming language. It is very simple to use.
It is an excellent language to learn programming for beginners.'


# Use count method with searching argument
print("The word 'is' appeared %d times" %(strVal.count("is")))
# Use count method with searching argument and starting position
print("The word 'is' appeared %d times after the position 20" %(strVal.count("is", 20)))
# Use count method with searching argument, starting position and ending position
print("The word 'is' appeared %d times within 50 to 100" %(strVal.count("is", 50, 100)))

Output:

Use of len() method

len() method is used to count the total number of characters in a string.

Syntax:

len(string)

This method takes any string value as an argument and returns the total number of characters of that string.

Example:

In the following script, a string variable named strVal is declared with a string data. Next, the value of the variable and the total number of characters that exist in the variable will be printed.

#!/usr/bin/env python3

# Define a string value
strVal="Python is easy to learn for the beginner."

# Print the string value
print("The string value:",strVal)
 
# Apply the len() method
print("Total characters:",len(strVal))

Output:

Use of index() method

index() method works like find() method but there is a single difference between these methods. Both methods return the position of the search text if the string exists in the main string. If the search text does not exist in the main string then find() method returns   -1 but index() method generates a ValueError.

Syntax:

string.index(search_text [, start [, end]])

This method has three arguments. The first argument is mandatory that contains the search text. The other two arguments are optional that contains the start and end position of searching.

Example:

index() method is used for 4 times in the following script. try-except block is used here to handle the ValueErrorIndex() method is used with one argument in the first output that will search the word, ‘powerful’ in the variable, strVal. Next, the index() method will search the word, ‘program’ from the position 10 that exists in strVal. Next, the index() method will search the word, ‘is’ within the position 5 to 15 that exists in strVal. The last index() method will search the word, ‘his’ within 0 to 25 that does not exist in strVal.

#!/usr/bin/env python3

# Define the string
strVal = 'Python is a powerful programming language.'

# Apply index() method with different arfuments
try:
   
    print(strVal.index('powerful'))
    print(strVal.index('program',10))
    print(strVal.index('is', 5, 15))
    print(strVal.index('his', 0, 25))
# Catch value error and print the custom message
except ValueError:

    print("The search string is not found")

Output:

Conclusion:

The most used built-in python methods of the string are described in this article by using very simple examples to understand the uses of these methods and help the new python uses.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.