q Python String Methods strip(), maketrans(), partition(), replace(), rfind(), rindex(), rjust()
codingstreets
Search
Close this search box.
python-string-methods-strip-maketrans-partition-replace-rfind-rindex-rjust

Python String Methods strip(), maketrans(), partition(), replace(), rfind(), rindex(), rjust()

In this article, learn about essential Python string methods like strip(), maketrans(), partition(), replace(), rfind(), rindex(), and rjust(). Discover how these methods can manipulate and modify strings to enhance your Python programming skills. Understand the purpose and functionality of each method, along with practical examples and use cases. Level up your string manipulation capabilities and become more proficient in handling and transforming text data in Python with these powerful string methods.

Before moving ahead, let’s see Python String Methods.

Table of Contents

strip() method

strip() returns the original string after removing the unnecessary characters.

Syntax – string.strip( characters )

Parameter Values –

characters – Optional. A set of unnecessary characters is to be removed.

Return Types

The return type of the strip() method in Python is a string that only depends on the parameter.

  • If character parameters are not provided, any whitespaces at the front and end of the string will be truncated, and the original string will be returned without white space at the front and the end.

  • If character parameters are not provided, and if there are no white spaces at the front and end of the string, then the original string will be returned as it is.

  • If a character parameter is provided, and if the matching character is available at the front and end of the string, then they will be removed, and the rest of the string will be returned.

  • If a character parameter is provided, and if the matching character is not available at the front and end of the string, then the string will be returned as it is.

Example:

				
					text1 = '    Hello'
text2 = ' How are you?'

print(text1+text2)

#output:
    Hello How are you?
				
			

Example: Returns the removed spaces to the left of the string.

				
					text1 = '    Hello'
text2 = ' How are you?'
text1 = text1.strip()

print(text1+text2)

#output:
Hello How are you?
				
			

Explanation: Removed the unnecessary characters from the beginning and end of the string.

Example: Removed the whitespaces from the beginning and end of the string.

				
					text = "   Hello,     "
text = text.strip('')

print(text)

#output:
   Hello,     
				
			

Example:

				
					text = "Hello,"
text = text.strip('')

print(text)

#output:
Hello,
				
			

Example: Removed the matches’ unnecessary characters.

				
					text = ",,,,,Hello, Python>>>>"
text = text.strip(',>')

print(text)

#output:
Hello, Python
				
			

Example: Remove if the matches’ unnecessary characters.

				
					text = ">>>>Hello<<<<"
text = text.strip(',')

print(text)

#output:
>>>>Hello<<<<
				
			

maketrans() method

maketrans() returns a mapping table for translation to be used in translations.

Syntax – string.maketrans(x[, y[, z]]). 

Variable y and z are optional arguments.

x – x is the first argument passed in the dictionary.

y – y is the second argument and passed it in string.

z – z is the third argument and passed it as mapping to none.

Example: Passed an argument as the dictionary.

				
					dict = {"x": "123", "y": "456", "z": "789"}
string = "xyz"
print(string.maketrans(dict))

#output:
{120: '123', 121: '456', 122: '789'}
				
			

Explanation: The dictionary contains the mapping characters for x, y, and z to 120, 121, and 122 respectively.

Example: Passed an argument as the string.

				
					str1 = "abc"
str2 = "pqr"
str3 = "xyz"
print(str3.maketrans(str1, str2))

#output:
{97: 112, 98: 113, 99: 114}

				
			

partition() method

partition() searches specified string, and splits the string into three characters containing a tuple.

First part – Returns the part before the split. In other words, from starting to till the point split

Second part – Returns the split part or specified string.

Third part – Returns the part after the split. In other words, from the point after the split to till last.

Syntax – string.partition( value )

Parameter Values –

value – Required. It searches for strings.

Note: This method searches for the first occurrence of the specified string.

Example: Search the specified word and split the string into three elements.

				
					text = 'python is a programming language'
split = 'programming'

print(text.partition(split))

#output:
('python is a ', 'programming', ' language')
				
			

Example: Check If the specified value is found in the string.

				
					text = 'python is a programming language'
split = 'computer'

print(text.partition(split))

#output:
('python is a programming language', '', '')
				
			

Explanation: Replaced not found string with two empty strings.

replace() method

replace() returns the replaced string of the original string.

Syntax – string.replace(old string, new string, count)

Parameter Values –

old string – Required. The string is to be changed into a new string.

new string – Required. The string which changed old string.

count – Optional. It specifies the number of occurrences of the old value to be replaced. By default, it counts all occurrences.

Example: Replace the old string with the new string.

				
					text = 'python is a programming language.'
print(text.replace('programming', 'computer'))

#output:
python is a computer language.
				
			

Example: Replaces all occurrences of the string.

				
					text = 'computer is a computer.'
print(text.replace('computer', 'python'))

#output:
python is a python.
				
			

Example: Replace the string between the range.

				
					text = 'computer is a language.'
print(text.replace('computer', 'python', 1))

#output:
python is a language.
				
			

rfind() method

rfind() returns the highest index number of the first most last occurrence specified substring else return -1.

Note: rfind() and rindex() method is almost the same but the difference is that rfind() returns -1 if the value is not found but rindex() raised an error.

Syntax – string.rfind( value, start, end )

Parameter Values –

value – Required argument to search for.

start – Optional argument for at what position the search is started. If no position to start, the default is 0.

end – Optional argument for at what position the search ends. The default is to the end of the string.

Example: Check if the substring is found in the string.

				
					text = 'python is a language.'
find = text.rfind('a')

print(find)

#output:
17
				
			

Example: Check if the substring is found in the string within a range.

				
					text = 'python is a language.'
find = text.rfind('a', 5, 20)

print(find)

#output:
17
				
			

Example: Check if the value is not found else return an error.

				
					text = 'python is a language.'
find = text.rindex('A')

print(find)

#output:
ValueError: substring not found
				
			

rindex() method

rindex() returns the index number of the last occurrence of the specified substring.

Syntax – string.rindex(value, start, end)

Parameter Values –

value – Required. Specify value search for.

start – Optional. At what position start for.

end – Optional. At what position end for.

Example: Returns the last occurrence index number of the substring.

				
					text = 'python is a language.'
find = text.rindex('n')

print(find)

#output:
14
				
			

Example: Returns the last occurrence index number of the substring within a range.

				
					text = 'python is a language.'
find = text.rindex('n', 5, 10)

print(find)

#output:
5
				
			

Note: rindex() and rfind() method is almost the same but the difference is that rindex() raised an error if the value is not found whereas rfind() returns -1.

Example: Check if the value found else returns an error.

				
					text = 'python is a language.'
r_index = text.rindex('A')

print(r_index)

#output:
ValueError: substring not found
				
			

rjust() method

rjust() fills the string from the left side with the specified character. The default fill character is whitespace.

Syntax – string.rjust( length, character)

Parameter Values –

length – Required. Returns the length of the given string. 

character –  Optional. It takes the character to fill the left missing space of the string.

Example: Returns the string filled with the default character – whitespace.  

				
					text = 'Python'
r_just = text.rjust(15)

print(r_just)

#output:
         Python
				
			

Example: Returns the string filled with the specified character.

				
					text = 'Python'
r_just = text.rjust(15, '>')

print(r_just)

#output:
>>>>>>>>>Python
				
			

Conclusion

Understanding and mastering these string methods can greatly enhance your ability to manipulate and process text data in Python. By leveraging these methods, you can perform a wide range of string operations, including cleaning input, searching for patterns, replacing text, and formatting output. Incorporating these methods into your programming repertoire will make you more proficient in working with strings and enable you to write more efficient and effective Python code.

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on