| by Arround The Web | No comments

Python String Operations

String operations are important concepts in Python for several reasons such as it is used in data processing, string formatting, text manipulation, and others.  We can perform different operations on Python strings for example, concatenated, sliced, formatted, searched, replaced, and more using built-in methods and functions. In this article, we, will discuss the following terms in detail using several examples:

What is Python String?

Python String Operations

Some Others Python String Operation Methods

Conclusion

What is Python String?

In Python, the “String” refers to the sequence of characters/letters. For instance, the string “Python” has the sequence characters “P”, “y”, “t”, “h”, “o” and “n”. All these characters are placed inside the single, double, or triple (in the case of a multiple-line string) quotes. Here is an example of a string:

# String Using Single Quotes
String1 = 'Python'
# String Using Double Quotes
String2 = "Python"
# String Using Triple Quotes
String3 = '''Python
Guide'
''

 

Here, we have created the string using single, double, and triple quotes. The triple quotes are used for creating multiple strings.

Python String Operations

There are multiple string operation methods found in Python. All these methods retrieve new strings instead of changing the original/given string. We will discuss some of the important string operations using different Python methods:

Example 1: Joining Multiple Strings in Python

The concatenation operator “+” is used in Python to join or concatenate two or more than two strings. Here in the below code, the “+” operator joined the given two strings “str1” and “str2”:

str1 = "Joseph"
str2 = "David"
# using + operator
print(str1 + ' ' + str2)

 

The following output verifies the concatenation operation:

Example 2: Replacing Substring of Python Strings

We can replace the substring from the given string using the “replace()” method. In the below code, the “string.replace()” method replaces the “Joseph” substring with the “Jon” substring in the given string:

str1 = "Hi, Joseph and Anna"
print('Original String: ', str1)
print('After Replacement: ',str1.replace("Joseph", "Jon"))

 

The string after the replacement operation is shown below:

Example 3: Retrieving String Length in Python

To get the string length the len()” method is used in Python. Consider the below code, where the “len()” function takes the “str1” string and retrieves the total length:

str1 = "Hi, Joseph and Anna"
print('Original String: ', str1)
print('Length of String is: ',len(str1))

 

Here is the output:

Example 4: Formatting Strings in Python

Formation of the string is done through various methods in Python such as “format()” and “format_map()” methods. Here, in this code, the “string.format()” method formats the string by placing the variable value inside the string using placeholder “{}”:

str1 = "Python"
print('Welcome to {} Guide'.format(str1))

 

The below output shows the string after formation:

Example 5: Looping Through Strings in Python

To loop or iterate through the given strings the “for loop” is used in Python. In the following code, we iterated over the string “str1” and displayed the string element to the output:

str1 = "Python"
# iterating through the string
for i in str1:
    print(i)

 

Here is the string element value:

Example 6: Comparing Two Strings in Python

Comparing strings is also considered an essential operation in Python. Different operators such as <, >, ==, etc. are used to compare two Python strings. For example, in this code, we compare the strings and check whether they are equal or not:

str1 = "Python Guide"
str2 = "Linux Guide"
str3 = "Python Guide"
# comparing str1 and str2
print(str1 == str2)

# comparing str1 and str3
print(str1 == str3)

 

The “True” indicates that the two values are equal and the “False” specifies that the values are not equal:

Example 7: Converting String to Uppercase and Lowercase

The “upper()” and “lower()” methods in Python are used to convert the given string into uppercase and lowercase characters. This example code transforms the given string with some upper and lower case letters to all upper and all lower with the “upper()” and “lower()” methods:

str1 = "PyThon GuIdE"
print('Given String: ',str1)
print('\nUpper Case String: ',str1.upper())
print('\nLower Case String: ', str1.lower())

 

Here is the output:

Example 8: Retrieving Encoded Strings in Python

To retrieve the encoded string, the “str1.encode()” method is used in Python. In this code, we apply the encode() method to the “str1” and retrieve the encoded version of the string:

str1 = "My name is Annå"
print('Original String: ', str1)
print('\nEncoded String: ', str1.encode())

 

The following output displays the encoded string:

Example 9: Finding Specified Substring in the Python String

Another useful operation in Python is finding the specified value from the given string. The find()” method is used to search/find the particular substring in the input string. The below code searches the “Python” substring from the input string “str1” using the “str.find()” method:

str1 = "Welcome to Python Guide."
print('Original String: ', str1)
print('\nString Index Position: ', str1.find("Python"))

 

The index value of the specified substring has been displayed:

Example 10: Splitting Strings in Python

We can perform a splitting operation on the input string by using the string.split()” method. This method splits the string and retrieves the list according to the species separator. If the separator is not provided the split() method splits the string from the space. In the below code, we split the given string from space value, with separator value, and with the max split parameter. Execute the below code to see the output:

str1 = "Welcome to Python Guide."
print(str1.split(), '\n')
# Using Separator Value
str2 = "Welcome@to@Python@Guide."
print(str2.split('@'), '\n')
# Using Maxsplit Parameter
print(str2.split('@', 2))

 

The below strings retrieved to the output after performing splitting operations:

Example 11: Determining Numeric Characters in the String in Python

We can check the given string whether it is numerical or not in Python by using the “string.isnumeric()” method. This method retrieves the True if the string is numerical and False if it is not. Look at the below code to understand how this method works:

str1 = "1947"
print(str1.isnumeric())

str2 = "1947 Year"
print(str2.isnumeric())

 

The above code shows this to the console:

Some Others Python String Operation Methods

There are other various string operations methods that are used in Python. Let’s have a look at these methods with their description:

Methods Descriptions
rpartition() Retrieves the tuple where the string is parted into three parts.
rstrip() This method retrieves the string with the right trim.
startswith() and endswith() These methods retrieve “True” if the string starts with the specified value and ends with the specified value.
index() This method returns the index position for the particular value by searching it in the given string.
isdigit() Retrieves True if the specified string characters are digits.
rfind() Retrieve the specified value’s last index position after searching it in the given string.
rjust() This method retrieves the string version with the right justified.
ljust() This method retrieves the string with the left justified version.
isdecimal() Retrieves True if input string characters are decimals.
capitalize() This method converts/transforms the first character to Uppercase.
casefold() This method transforms the string into small letters.
count() This method retrieves the occurrences of specified values found in the string.
rsplit() It starts from the right and splits the string into a list.
translate() Returns the translated string of the given string.
rindex() Find the value in the given string and retrieve the last position.
isupper() Retrieve True if the given string characters are upper case.
isascii() Retrieve True if the given string characters are ASCII characters.
format_map() Format the value in the specified string.
maketrans() This method returns a translation table.
splitlines() Returns a list by splitting the string at line breaks.
swapcase() This method retrieves the swap cases by changing the lowercase with uppercase.
zfill() This method pads the “0” value at the beginning of the specified number.

Conclusion

You can use different sets of Python methods to perform a String operation such as joining strings, splitting strings, searching substrings, and others. The for loop is used to iterate/loops over the string and retrieve elements to output. This guide presented a comprehensive explanation of various string methods such as find(), split(), format(), encode(), isnumeric(), and others.

Share Button

Source: linuxhint.com

Leave a Reply