Skip to content
Home » Programming » String Functions in Python

String Functions in Python

string-functions-in-python

In this post, we will be discussing some of the string functions available in Python. In Python, there are various operations or functions available or built-in that we can use to work with strings.

String Concatenation

We can concatenate two strings together using the ‘+‘ operator (an operator is an operation or behavior that can be applied to the types involved). That means we can take one string and add it to another string to create a new third string or simply display them on the screen.

string_1 = 'Good'
string_2 = "Morning"
string_3 = string_1 + string_2
print (string_3)
print ('Hello' + 'World')

The output for the above code will be given as

Good Morning
Hello World

Notice that the way in which the string is defined does not matter here, string_1 used single quotes but string_2 used double quotes; however they are both just strings.

Length of a String

It can sometimes be useful to know how long a string is, for example if you are putting a string into a user interface you might need to know how much of the string will be displayed within a field. To find out the length of a string in Python we use the len() function. For example,

print (len(string_3))

This will print out the length of the string currently being held by the variable string_3 (in terms of the number of characters contained in the string including spaces).

Accessing a Character

As a string is a fixed sequence of letters, it is possible to use square brackets and an index (or position) to retrieve a specific character from within a string. For example,

my_string = 'DroxElement'
print(my_string[3])

However, we should keep in mind that strings are indexed from 0 (zero). This means that the first character is in position 0, the second character in position in 1, and so on. Thus stating [3] indicates that we want to obtain the fourth character in the string, which in this case is the letter ‘x’. This form of indexing elements is actually quite common in programming languages and is referred to a zero based indexing.

Accessing a Subset of Characters

It is also possible to obtain the subset of the original string, often referred to as a sub-string (of the original string). This can again be done using the square brackets notation but using a ‘:‘ symbol to indicate the start and end points of the sub-string. If one of the positions is omitted then the start or end of the string is assumed (depending upon the omission). For example,

my_string = "DroxElement"
print (my_string[3])            # character at position 3
print (my_string[1:5])         # from position 1 to 5
print (my_string[:5])           # from start to position 5
print (my_string[2:])           # from position 2 to the end

This will generate the output as

x
roxE
DroxE
oxElement

As such my_string[1:5] returns the substring containing the 2nd to 5th letters (that is ‘roxE‘). In turn my_string[:5] returned the sub-string containing the 1st to 5th letter and my_string[2:] the sub-string containing the 3rd to the last letters.

Repeating Strings

We can also use the ‘*‘ operator with strings. In the case of strings this means repeat the given string a certain number of times. This generates a new string containing the original string repeated n number of times. For example,

print ('*' * 10)
print ('#' * 10)
print ('Hi' * 10)
print ('World' * 5)
print ('DroxElement' * 2)

This will generate the result or output as

**********
##########
HiHiHiHiHiHiHiHiHiHi
WorldWorldWorldWorldWorld
DroxElementDroxElement

Splitting Strings

A very common requirement is the need to split a string up into multiple separate strings based on a specific character such as a space or a comma. This can be done with the split() function, that takes a string to used in identifying how to split up the receiving string. For example,

title = "Drox Element, Space for Programming"
print ('Source string: ', title)
print ('Split using a space')
print (title.split(' '))
print ('Split using a comma')
print (title.split(','))

This produces as output

Source string:  Drox Element, Space for Programming
Split using a space
['Drox', 'Element,', 'Space', 'for', 'Programming']
Split using a comma
['Drox Element', ' Space for Programming']

As can be seen from this, the result generated is either a list of each word in the string or three strings as defined by the comma. The thing to notice something odd is about the way in which we wrote the call to the split operation. We did not pass the string into split() rather we used the format of the variable containing the string followed by ‘.‘ and then split().

This is because split() is actually what is referred to as a method. We will return to this concept more when we explore classes and objects. For the moment merely remember that methods are applied to things like string using the dot notation. For example, given the following code

title = "Drox Element, Space for Programming"
print (title.split(' '))

This means take the string held by the variable title and split it based on the character space.

Counting Strings

It is possible to find out how many times a string is repeated in another string. This is done using the count() operation. For example,

my_string = " D r o x E l e m e n t        "
print ("Total space count = ",my_string.count(' '))

which has the output indicating the total number of spaces in the original string as

Total space count = 19

Replacing Strings

One string can replace a sub-string in another string. This is done using the replace() method on a string. For example,

my_string = "DroxElement"
print (my_string.replace("Element","Programming"))

The output produced by this is thus

DroxProgramming

Finding Sub Strings

We can find out if one string is a sub-string of another string using the find() method. This method takes a second string as a parameter and checks to see if that string is in the string receiving the find() method. The linguistic structure to execute find() method is

string.find (string_to_find)

The method returns -1 if the string is not present. Otherwise it returns an index indicating the start of the sub-string. For example,

print ('DroxElement, Space for Programming'.find('Programming'))

This prints out the value 23 (the index of the first letter of the substring ‘Programming’); thus the first letter is at position zero, the second at position one and so on based on zero indexing.

In contrast, the following call to the find() method prints out -1 as ‘Programming’ is no longer part of the target string.

print ('DroxElement, Space for Coders'.find('Programming'))

Converting Other Types into Strings

If we try to use the ‘+‘ concatenation operator with a string and some other type such as a number then we will get an error. For example, if we try the following code snippet:

msg = 'DroxElement is number ' + 1
print (msg)

We will get an error message indicating that we can only concatenate strings with strings not integers with strings. To concatenate a number such as 1 with a string we must convert it to a string. This can be done using the str() function. This contest any type into a string representation of that type. For example,

msg = 'DroxElement is number ' + str(1)
print (msg)

This code snippet will print out the message:

DroxElement is number 1

Comparing Strings

To compare one string with another we can use the ‘==‘ (equality) and ‘!=‘ (not equals) operators. These will compare two strings and return either True or False indicating whether the strings are equal or not. For example,

print ('DroxElement' == 'DroxElement')   # prints True
print ('DroxElement' == 'ElementDrox')   # prints False
print ('DroxElement' != 'ElementDrox')     # prints True
print ('droxelement' == 'DroxElement')    # prints False

We should note that strings in Python are case sensitive thus the string ‘droxelement’ does not equal the string ‘DroxElement’. Thus, the output for the above code snippet is

True
False
True
False

Also Read: Variables, Constants and Literals in Python

Other String Operations

There are in fact very many different operations available for strings, including checking that a string starts or ends with another string, that is it upper or lower case etc. It is also possible to replace part of a string with another string, convert strings to upper, lower or title case etc. For example,

my_string = "Drox Element"
print ('Testing a String')
print ('-' * 20)
print ('Original string : ',my_string)
print ('Does the original string starts with "D" ?', my_string.startswith('D'))
print ('Does the original string starts with "d" ?', my_string.startswith('d'))
print ('Does the original string ends with "t" ?', my_string.startswith('t'))
print ('Does the original string ends with "T" ?', my_string.startswith('T'))
print ('Does the original string has title form?', my_string.istitle())
print ('Does the original string is in upper case?', my_string.isupper())
print ('Does the original string is in lower case?', my_string.islower())

print ('String Conversions')
print ('-' * 20)
print ('Original string in upper case : ', my_string.upper())
print ('Original string in lower case : ', my_string.lower())
print ('Original string in title case : ', my_string.title())
print ('Original string in swapcase : ', my_string.swapcase())

The output from this is

Testing a String
--------------------
Original string :  Drox Element
Does the original string starts with "D" ? True 
Does the original string starts with "d" ? False
Does the original string ends with "t" ? False
Does the original string ends with "T" ? False
Does the original string has title form? True
Does the original string is in upper case? False
Does the original string is in lower case? False
String Conversions
--------------------
Original string in upper case :  DROX ELEMENT
Original string in lower case :  drox element
Original string in title case :  Drox Element
Original string in swapcase :  dROX eLEMENT

Python suited IDE: Visual Studio Code

Leave a Reply

Your email address will not be published. Required fields are marked *