Home Python Basic operations on Python strings

Basic operations on Python strings

Strings are one of the most important data types in any programming language. They are used for storing text like names of persons, places, etc. In Python, strings can be created by writing them under triple quotes, double quotes, or single quotes. Unlike C++, strings in Python can also be written under single quotes. Python also supports Multiline strings that can be written by enclosing text in triple quotes.

In this tutorial, we will learn to create strings in python and perform basic operations on strings in python. We will discuss each function with an example code and also explain it for better understanding. It is recommended to run each code on your computer by using a python interpreter. It is also recommended to use an IDE like the open-source Visual Studio Code for writing code more efficiently. Now, let us begin our tutorial by looking at how to create a string.

Creating a string in python

In python, we can create a string by simply writing text under double quotes or single quotes. See the below code for an illustration.

# Creating a string using double quotes
name = "CodeUnderscored"
# Creating a string using single quotes
location = 'Internet'
# Displaying the strings
print(name)
print(location)

In the above code, First, we create a string by enclosing a text under double-quotes. Then, we again created a string in the next line, but we enclosed the text in single quotes. At last, we used the print() function of python to display the string to the console. On running the above code, we will get the output as shown in the below image.

creating a single lne string in python
creating a single-line string in python

We can only convert a single-line text into a string using the single quotes or double quotes of python. But python also supports Multiline strings, which can be created by enclosing the text under triple quotes. The below code shows a practical illustration of creating a multiline string in python.

# Creating a multiline string
multi = """
CodeUnderscored is a website where
you can learn Coding in different 
languages like C++, python, Javascript, etc.
"""
# displaying the multiline string
print(multi)

In the above code, we created a multiline string by enclosing some text under triple quotes and store the created string into a variable. Then we use the print() function of python and pass the string variable as its argument. This will display the created multiline string into the console. On running the above code, we will get an output as shown in the below image.

creating a multi line string in python
creating a multi-line string in python

Calculating the length of a string

In python, we can easily calculate the length of a string. This is because python provides a built-in len() function that can calculate the length of a string. In addition, we can also calculate the length of the string using the for loop of python. Let us discuss each of the methods in more detail.

Using len function

Python provides a built-in len() function for calculating the length of python objects like string, list, tuples, etc. The len() function accepts a python object as its argument and returns the length of that object in the form of an integer. The below code shows a practical demonstration of using the len() function.

# creating a string
name = "Codeunderscored"
# getting the length of the string
length = len(name)
# displaying the length
print("[+] The length of ", name, " is : ", length)

In the above code, we first created a string and stored it into a variable. Next, we use the len() function of python and pass the string variable as its argument. Then, we also created another variable and stored the return value of the len() function into the variable. At last, we use the print() function of python to display the length of the string to the console. On running the above code, we will get the output as shown in the below image.

calcuating the length of a string using the len() function
calculating the length of a string using the len() function

Using for loop

We can also calculate the length of a string in python by using the for loop of python. The below code illustrates calculating the length of a string using the for loop of python.

# creating a string
name = "Codeunderscored"
# calculating the length of the string
length = 0
for i in name:
    length = length + 1
# displaying the length
print("[+] The length of ", name, " is : ", length)

In the above code, we first created a string and stored it in a variable. Next, we created a counter variable and initialized it with zero. After that, we iterate over the elements of the strings and increment the value of length by one for each iteration. After completing the for loop, we will get the length of the string in the counter variable. At last, we display the value of the counter variable using the print() function of python. On running the above code, we will get the output as shown in the below image.

calculating the length of a string using the for loop of python
calculating the length of a string using the for loop of python

Merging Strings

In python, merging or concatenation of a string can be done by using the + operator. The + operator is handy in python and can merge python objects like strings, lists, etc. The below code shows the demonstration of combining strings using the + operator.

# creating strings
first = "Codeunderscored"
second = "is a good website"
third = "to learn programming"
print("[+] Before Merging\n")
print(first)
print(second)
print(third)
# Performing the concatenation of strings
new = first + " " + second + " " + third
print("\n[+] After Merging\n")
print(new)

In the above program, we created three strings and stored them in three variables. Then, we displayed each of the strings into the terminal using the print() function. After that, we merge the three strings using the + operator and store the combined string into a variable. At last, we print the merged string by accessing it from the variable using the print() function. On running the above code, we will get the output as shown in the below image.

merging two or more strings
merging two or more strings

Changing cases of a string

Python provides many built-in functions that can be used to change the cases of a string. Some functions and methods are lower(), upper(), title(), swapcase(), etc. Let us discuss them with examples.

lower()

The lower() method is used to change all the characters of a string into lowercase. See the below code for example.

# creating a string in python
word = "CODEunderscored"
# changing the string to lowercase and displaying it to the console
print(word.lower())

We first created a string in the above code and then used the lower() method to lowercase. Therefore, on running the above code, we will get the output as shown in the below image.

changing a python string into lower case using the lower() method
changing a python string into the lower case using the lower() method

upper()

The upper() method is used to change a string into uppercase. See the below code for example.

# creating a string in python
word = "CODEunderscored"
# changing the string to uppercase and displaying it to the console
print(word.upper())

In the above code, we created a string and then used the upper() method to change it into uppercase. Therefore, on running the above code, we will get the output as shown in the below image.

changing a python string into upper case using the upper() method of python
changing a python string into the upper case using the upper() method of python

Swap Case

Python also has a built-in method to swap the case of a string. Using the swapcase() method, the letters in uppercase will change to lowercase and vice versa. The below code shows a practical demonstration of using the swapcase() method.

# creating a string in python
word = "CODEunderscored"
# swapping the case of a string and displaying it to the console
s = word.swapcase()
print(s)

In the above code, we have created a string and then used the swapcase() method to swap the case of each letter of the string. Therefore, on running the above code, we will get the output as shown in the below image.

swapping the case of a string using the swapcase() method of python
swapping the case of a string using the swapcase() method of python

Checking the Cases of Strings

Python also provides built-in methods to check the case of a string. Let us discuss the ways that can be used to check if a string is lowercase or uppercase.

isupper()

The isupper() method is used to check if a string is uppercase in python. It returns True if the string is in uppercase, else it returns False. See the below code for an illustration.

# Creating some python strings
word1 = "CODEunderscored"
word2 = "CODEUNDERSCORED"
# Checkingthe string for uppercase
print(word1.isupper())
print(word2.isupper())

In the above code, we first created two strings and then used the isupper() method to check whether the strings are in uppercase. Then we print the return value of the isupper() function using the print function. Thus, on running the above code, we will get the output as shown in the below image.

checking if the case of a string is uppercase using the upper() function
checking if the case of a string is uppercase using the isupper() function

islower()

The islower() method is used to check if a string is lowercase in python. It returns True if the string is in lowercase, else it returns False. See the below code for illustration.

# creating some random strings
word1 = "CODEunderscored"
word2 = "codeunderscored"
# Checking the string for lowercase
print(word1.islower())
print(word2.islower())

In the above code, we first created two strings and then used the islower() method to check lowercase strings. Then we print the return value of the islower() function using the print() function of python. On running the above code, we will get the output as shown in the below image.

checking if the case of a string is lowercase in python
checking if the case of a string is lowercase in python

Counting the number of occurrences of a character

We can also count the number of occurrences of a character in a string. Python provides a built-in count() function that can count the number of occurrences in a string. The below code shows a practical illustration of using the count() function.

# creating a python string
word = "codeunderscored"
# counting the number of occurences of e in the string
c = word.count('e')
# displaying the count
print(f'The number of occurences of the character is : {c}')

In the above code, we created a single line string and stored it in a variable. Then we use the count() method of the string to count the number of occurrences of the letter e in the string. On running the above code, we will get the output as shown in the below image.

counting the occurences of a characyer in a string using the count() method
counting the occurrences of a character in a string using the count() method

Splitting a string

Python provides a built-in method, split(), that can split a string concerning a delimiter. The split() method accepts the delimiter as its argument, splits the string, and converts it into a list. The following example shows a practical demonstration of splitting a string.

# creating a multi word string
word = "Codeunderscored is the best place to learn coding"
# splitiing the string and transforming it into a list
l = word.split(' ')
print(l)

In the above code, first, we created a string and stored it into a variable. Next, we use the split() method of the string with space as its argument. This will split the string by its space and turn the individual words into a list item. On running the above code, we will get the outputs shown in the below image.

splitting a string in python using the split() method
splitting a string in python using the split() method

String Indexing

String indexing is one of the most effective operations of a string in python. In string indexing, we can access a character of the string by passing the index in square brackets. The below code block shows a practical demonstration of indexing in strings.

# creating a python strings
word = "Codeunderscored"
print(word)
# accessing the characters of the string using indexing
print("The character at the index 0 is : ",word[0])
print("The character at the index 1 is : ",word[1])
print("The character at the index 4 is : ",word[4])
print("The character at the index 8 is : ",word[8])

In the above code, we first created a string and stored it into a variable. Next, we use the indexing of string and selecting the character at the provided index. On running the above code, we will get the output as shown in the below image.

selecting a character using indexing of strings
selecting a character using indexing of strings

We can also use negative indexing in strings in python. The below code shows the demonstration of the negative indexing.

# creating a python string
word = "Codeunderscored"
print(word)
# accessing the characters of the string using indexing
print("The last character of the string is : ",word[-1])
print("The second last character of the string is : ",word[-2])
print("The third last character of the string is : ",word[-3])
print("The forth last character of the string is : ",word[-4])
print("The fifth last character of the string is : ",word[-5])

In the above code block, we use negative indexing in place of positive indexing. So, in the above code, the indexing is done starting from the end of the string. So, on running the above code, we will get the output as shown in the below image.

selecting a character using negative indexing of strings
selecting a character using negative indexing of strings

String Slicing

Python also has another type of selection technique for strings. In the slicing of strings, we can choose a substring of the parent string by given the starting index and the end index of the sub-string. The below code shows a practical demonstration of string slicing.

# creating a python string
word = "Codeunderscored"
# accessing a substring from a python string
print(word[1:9:1])
print(word[1:9:2])
print(word[1:9:3])
print(word[1:9])

We use the string slicing technique to select a substring from the given string in the above code. On running the above code, we will get the output as shown in the below image.

selecting substring from a parent string using string slicing
selecting substring from a parent string using string slicing

String reversing

Strings reversing is one of the most critical operations of strings. There are no built-in methods to perform string reversing in python. We can use the string slicing technique that we discussed above for performing string reversing. The below code shows a practical demonstration of string reversing.

# creating a python string
word = "Codeunderscored"
# reversing the string and displaying it to the console
print(f"The reverse of {word} is {word[::-1]}")

On running the above code, we will get the output as shown in the below image.

reversing a string using string slicing
reversing a string using string slicing

Conclusion

In this tutorial, we learned about the strings in python. We have seen how to create strings in python and perform some basic operations on strings. You may also want to see our tutorial on performing basic operations in python lists.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More