All IT Courses 50% Off
Python Tutorials

Working with Strings in Python: Replace, Join, Split, Uppercase, and Lowercase

Strings are one of the most frequently used data types in Python. As a python programming, it becomes extremely crucial to know how to work with strings and wrangle them to a desired form. In this tutorial, you will learn about the various functions and methods that can be called on a string and what exactly they do. In specific terms, these are what you will learn by the end of this tutorial. 

  • Accessing substrings through indexing and slicing
  • Concatenation of Strings
  • Replacing a String with another String
  • Changing Uppercase to Lowercase and Vice Versa
  • Understanding the Join method. 
  • Reversing a String
  • Splitting a String 

Let’s jump right into it. 

Accessing substrings through indexing and slicing

The characters in a string can be accessed through indexing, where the character is seen as the element of the string. For instance, in the string, ‘Python’, the characters P, y, t, h, o, and n are elements of the string and they can be accessed by indexing. 

If you do not understand the difference between indexing and slicing, indexing involves getting just one element in the list, i.e a character. Slicing on the other hand involves accessing more than one element at a time, i.e a substring.

  • When indexing, the syntax is given by string_variable[index]
  • When slicing, the syntax is given by, string_value[start_index:end_index] 

Python interpreters index from 0 to the number of elements in the string. So for a string, ‘Python’, each element/character will have the following index. 

All IT Courses 50% Off
  • ‘P’ has an index of 0
  • ‘y’ has index 1
  • ‘t’ has index 2
  • ‘h’ has an index of 3
  • ‘o’ has index 4
  • ‘n’ has an index of 5

Let’s take some examples.

#define some string
string = 'Python'
 
#access elements through indexing
print('INDEXING EXAMPLES')
print('string[0]: ', string[0])
print('string[2]: ', string[2])
print('string[4]: ', string[4])
 
print()
print('SLICING EXAMPLES')
#access substrings through slicing
print('string[0:3]: ', string[0:3])
print('string[2:4]: ', string[2:4])
print('string[1:2]: ', string[1:2])
Output:
INDEXING EXAMPLES
string[0]:  P
string[2]:  t
string[4]:  o

SLICING EXAMPLES
string[0:3]:  Pyt
string[2:4]:  th
string[1:2]:  y

Concatenation of Strings

In python, joining a string to another string is called concatenation. For instance, if there was a string, ‘H2k’ and another string, ‘Infosys’, they can be joined together to form H2KInfosys. So the question is, how is it done?

Concatenation is done with the + operator. Let’s go over to our IDE and see how it is done. 

#define two strings
string1 = 'H2k'
string2 = 'Infosys'
 
#concatenate both strings
print('string1 + string2: ', string1 + string2)
Output:
string1 + string2:  H2kInfosys

If you wish to add whitespace between both strings, you can add a string populated with just whitespace. See the example below. 

#concatenate both strings
print('string1 + string2: ', string1 + ' ' + string2)
Output:
string1 + string2:  H2kInfosys

Replacing a String with another String

Situations may arise where you need to replace a string with another string. The replace() method is used for this operation. Let’s say we have a string, ‘I am going to work’. If we wish to change it to ‘I am coming from work’, we can use the replace function as seen in the example below. 

#define a string
first_string = 'I am going to work'
#make the replacement
second_string = first_string.replace('going to', 'coming from')
 
print(second_string)
Output:
I am coming from work

Changing Uppercase to Lowercase and Vice Versa

The .upper() and .lower() are used to change a string to all uppercase letters and lowercase letters respectively. Let’s see some examples. Say we wish to change a string to uppercase.

#define a string
string = 'Learn Python at H2k Infosys'
 
#change to uppercase
print(string.upper())
Output:
LEARN PYTHON AT H2K INFOSYS

In the same vein, we can change a string in lowercase to uppercase with the .lower() method.

#define a string
string = 'LEARN PYTHON AT H2K INFOSYS'
 
#change to uppercase
print(string.lower())
Output:
learn python at h2k infosys

Understanding the Join method. 

The join method is used to insert a string separator in another string. It is an application in a situation where you wish to add some separator to an iterable object such as a string or list. Below is the docstring for the join method. 

Signature: string.join(iterable, /)
Docstring:
Concatenate any number of strings.
 
The string whose method is called is inserted in between each given string.
The result is returned as a new string.

Let’s see how to use the join method. 

#define some string
string = 'H2kInfosys'
 
#join each character of the string with an hyphen
joined_string = '-'.join(string)
print(joined_string)
Output:
H-2-k- -I-n-f-o-s-y-s

As seen, the separator is added to every character of the string.  Since, a list is also an iterable, you can call the join method on a list.

#create a list
list_1 = ['Data collection', 'Preprocessing', 'Model building', 'Model evaluation', 'Model deployment']
 
#join each element of the list with >>>
joined_list = '>>> '.join(list_1)
print(joined_list)
Output:
Data collection>>> Preprocessing>>> Model building>>> Model evaluation>>> Model deployment

Reversing a String

Python allows you to reverse the arrangement of the string using the reversed() method. It is important to point out that the reversed() method returns an object. To print the reversed string, you will need to join the reversed object with an empty string separator. Let’s see an example.

#define some string
string = 'H2kInfosys'
 
#reverse a string
string_reversed = ''.join(reversed(string))
print(string_reversed)
Output:
sysofnI k2H

Splitting a String 

You can split a string based on the occurrence of a character in that string using the split() method. For instance, a string data may be in the form 22/01/2021, you can get the day, month, and year by splitting by the forward-slash (/). The split() method returns a list of the split strings. 

string = '22/02/2021'
 
#split the string by /
string_split = string.split('/')
print(string_split)
Output:
['22', '02', '2021']

This can come in handy when preprocessing textual data. If you have a function and you wish to split the corpus into a list of sentences, you can easily split by a full stop. See the example below. 

string = '''John did not know anything about programming. 
            He however, wanted to learn Python.
            He discovered H2k Infosys on Twitter. 
            Consequently, he reads their tutorial and subscribes to a course. 
            Now, John is a guru in Python. 
            He works as a developer in a Fortune 500 company.
'''
 
#split the string by /
string_split = string.split('.')
print(string_split)
Output:
['John did not know anything about programming', ' \n            He however, wanted to learn Python', '\n            He discovered H2k Infosys on 
Twitter', ' \n            Consequently, he reads their tutorial and subscribes to a course', ' \n            Now, John is a guru in Python', ' \n 
           He works as a developer in a Fortune 500 company', '\n']

You can loop over the list to get a more appealing result. Let’s use a list comprehension to do this. 

#split the string by /
string_split = string.split('.')
[print(x) for x in string_split]
Output:
John did not know anything about programming
 
            He however, wanted to learn Python

            He discovered H2k Infosys on Twitter

            Consequently, he reads their tutorial and subscribes to a course

            Now, John is a guru in Python

            He works as a developer in a Fortune 500 company

In summary

You have discovered how to play around with strings in Python. You learned how to access characters and substrings of a string using indexing and slicing. Furthermore, we discussed how to replace a string, reverse a string, convert string characters to lowercase and uppercase, join separators to an iterator, and split a string by a character. If you have any questions, feel free to leave them in the comment section and I’d do my best to answer them.

Facebook Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Check Also
Close
Back to top button