- Define the String Variables
- Count the Length of the String
- Print the String
- Format the String
- Remove the Content from a String
- Split the String
- Trim the String
- Reverse the String
- Replace the String Value
- Change the Case of the String
Define the String Variables
The string value can be defined in three ways in the Python script: the single quotes (‘), double quotes (“), and triple quotes (”’). Create a Python file with the following script that defines three string variables and print the variables in the output:
string1 = 'Python programming'
#Define variable with double quotes to store single-line string
string2 = "Python is a weakly typed language"
#Define variable with triple quotes to store multi-line string
string3 = '''Learn Python programming
from the basic'''
#Print the variables
print(string1)
print(string2)
print(string3)
Output:
The following output appears after executing the script:
Count the Length of the String
Python has a built-in function named len() to count the length of the string variable. Create a Python file with the following script that takes a string value from the user, the print input value, and the length of the input value:
strVal = input("Enter a string value: ")
#Count the total characters of the input value
ln = len(strVal)
#Print the string value taken from user
print ("The string value is:", strVal)
#Print the length of the string
print ("The length of the string is:", ln)
Output:
According to the following output, “Python String” is taken from the user as an input value. The length of this string is 13 which is printed:
Print the String
Create a Python file with the following script that shows the methods of printing a single string value, one numeric and one string value, one variable with another string, and multiple variables with other strings. Three input values are taken from the user after executing the script.
print ("Learn Python")
#Print multiple values
print (15, " Python String Examples")
#Take three input values from the user
course_code = input("Enter the course code:")
course_name = input("Enter the course name:")
credit_hour = float(input("Enter the credit hour:"))
#Print a single variable
print ("\n","Course Code:", course_code)
#Print multiple variables
print (" Course Name:", course_name, "\n","Credit Hour:", credit_hour)
Output:
“CSE320”, “Python Programming”, and “2.0” are taken as input after executing the script. These values are printed later.
Format the String
Multiple options are available in Python to format the string values. The format() function is one of them. Different ways of using the format() function in the Python script are shown in the following script. The student name and the batch are taken from the user after executing the script. Next, these values are printed with other strings using the format() function with the key values and positional values.
name = input("Student name:")
#Take a number value from the user
batch = int(input("Batch:"))
#Use of format() function with the variables
print ("{n} is the student of {b} batch.".format(n = name, b = batch))
#Use of format() function with one string value and one numeric value
print ("{n} is the student of {s} semester.".format(n = "Jafar", s = 6))
#Use of format() function without defining positional keys
print ("{} is the student of {} batch.".format(name, 12))
#Use of format() function by defining numeric positional keys
print ("{1} is the student of {0} semester.".format(10,"Mazhar"))
Output:
The following output appears for the input values, “Mizanur Rahman” as the student name and 45 as the batch value:
Remove the Content from a String
The partial content or the full content of a string variable can be removed from the Python string variable. Create a Python file with the following script that takes a string value from the user. Next, the script removes the content of the input value partially by cutting the string like the previous example and making the undefined variable using the “del” command.
#Take a string value
strVal = input("Enter a string value:\n")
print ("Original string:" + strVal)
#Remove all characters from the string after
#the first 10 characters
strVal = strVal[0:10]
print ("String value after first delete:" + strVal)
#Remove 5 characters from the beginning of the string
strVal = strVal[5:]
print ("String value after second delete:" + strVal)
#Remove the particular character from the string if exists
strVal = strVal.replace('I', '', 1)
print ("String value after third delete:" + strVal)
#Remove the entire string and make the variable undefined
del strVal
print ("String value after last delete:" + strVal)
except NameError:
#Print the message when the variable is undefined
print ("The variable is not defined.")
Output:
The following output appears after executing the script:
Split the String
Create a Python file with the following script that splits the string value based on the space, colon (:), a particular word, and the maximum limit:
strVal = input("Enter a string value:\n")
#Split the string without any argument
print ("Split values based on the space:")
print (strVal.split())
#Split the string based on a character
print ("Split values based on the ':' ")
print (strVal.split(':'))
#Split the string based on a word
print ("Split values based on the word ")
print (strVal.split('course'))
#Split the string based on the space and the maximum limit
print ("Split values based on the limit ")
print (strVal.split(' ', 1))
Output:
The following output appears for the “course code: CSE – 407” input value after executing the script:
Trim the String
Create a Python file with the following script that trims the string based on the space from both sides, left side, and right side using the strip(), lstrip(), and rstrip() functions. The last lstrip() function is used based on the “P” character.
print ("Original string:" + strVal)
#Trim both sides
strVal1 = strVal.strip()
print ("After trimming both sides: " + strVal1)
#Trim left side
strVal2 = strVal.lstrip()
print ("After trimming left side: " + strVal2)
#Trim right side
strVal3 = strVal.rstrip()
print ("After trimming right side: " + strVal3)
#Trim left side based on a character
strVal4 = strVal2.lstrip('P')
print ("After trimming left side based on a character: " + strVal4)
Output:
The following output appears after executing the script:
Reverse the String
Create a Python file with the following script that reverses the value of the string value by setting the start position at the end of the string with the -1 value:
strVal = input("Enter a string value:\n")
#Store the reversed value of the string
reverse_str = strVal[::-1]
#Print both original and reversed values of the string
print ("Original string value: " + strVal)
print ("Reversed string value: " + reverse_str)
Output:
The following output appears for the “Hello World” input value:
Replace the String Value
Create a Python file with the following script that takes the main string, search string, and the replace string from the user. Next, the replace() function is used to search and replace the string.
strVal = input("Enter a string value:\n")
#Take the search string
srcVal = input("Enter a string value:\n")
#Take the replaced string
repVal = input("Enter a string value:\n")
#Search and replace the string
replaced_strVal = strVal.replace(srcVal, repVal)
#Print the original and replaced string values
print ("Original string:" + strVal)
print ("Replaced string:" + replaced_strVal)
Output:
The following output appears for the “Do you like PHP?” main string value, the “PHP” search value, and the “Python” replacement value:
Change the Case of the String
Create a Python file with the following script that takes the email address and password from the user. Next, the lower() and upper() functions are used to compare the input values with the particular values to check if the input values are valid or invalid.
email = input("Enter email address:")
#Take the password
password = input ("Enter the password:")
#Compare the string values after converting the email
#in lowercase and password in uppercase
if email.lower() == "[email protected]" and password.upper() == "SECRET":
print ("Authenticated user.")
else:
print ("Email or password is wrong.")
Output:
The following output appears for the “[email protected]” and “secret” input values:
The following output appears for the “[email protected]” and “secret” input values:
Conclusion
Different types of string-related tasks using different built-in Python functions are shown in this tutorial using multiple Python scripts. The Python users will now be able to get the basic knowledge of the Python string operations after reading this tutorial properly.