How to Implement and Play with Strings in Python

Published on Sep 19,2019 2.1K Views

How to Implement and Play with Strings in Python

edureka.co

When we play strings in Python programming language, we refer to a set of characters stored contiguously in memory, on which we can operate to manipulate the set of characters e.g. get a character at an index, replace a set of characters, convert from upper case to lower case and vice versa, etc.

 

What are strings in Python?

Strings in Python are instances of class <’str’>. This is an inbuilt class with many helper functions to operate on strings. Strings are immutable i.e. a string in Python cannot be modified once created. If you modify a string, it creates a new string in memory to store the modified string.

Find out the type of a literal string: Function type() returns type of a variable in python

s1 = "Hello There!"
print(type(s1))

Output:

<class ‘str’>

 

How to use strings, indexing, and slicing?

Different ways of initializing strings:

# Single quotes
str1 = 'Hi, Let us learn strings in Python'
print(str1)
# Double quotes
str1 = "Hi, Let us learn strings in Python"
print(str1)
 
# Single quotes within double, no need to escape them or match them
str1 = "Hello there, How's your friend? "
 
# Double quotes within single, no need to escape them or match them
str1 = 'Hello there, How is your friend "K"?'
str2 = 'Hello there, "How is your friend K?'
print(str1)
print(str2)
 
# triple quotes are multiline strings
str1 = '''Hello, welcome to
           strings in Python'''
print(str1)
 
str1 = """Hello, welcome to
           strings in Python"""
print(str1)

Output:

Hi, Let us learn strings in Python

Hi, Let us learn strings in Python

Hello there, How is your friend "K"?

Hello there, "How is your friend K?

Hello, welcome to

           strings in Python

Hello, welcome to

           strings in Python

 

Indexing and Slicing

Examples of Indexing and Slicing:

str1 = 'India, a nation of billion people'
print('str1: ', str1)
 
# print first character
print('Index 0: ', str1[0])
 
# print last character
print('Index -1: ', str1[-1])
 
# Slicing syntax [start : end : step]
# Slicing from 2nd to 4th character
print('Slice [1:5] = ', str1[1:5])
 
# Slicing 1st to 2nd last character
print('Slice [0:-2] = ', str1[0:-2])
 
# Splice a string to get characters at even index
print("Even index: ", str1[::2])
 
# Splice a string to get characters at odd index
print("Odd index: ", str1[1::2])
 
# Shortcut slicing to reverse a string
print('Reverse using slicing: ', str1[::-1])

Output:

str1:  India, a nation of billion people

Index 0:  I

Index -1:  e

Slice [1:5] =  ndia

Slice [0:-2] =  India, a nation of billion peop

Even index:  Ida aino ilo epe

Odd index:  ni,anto fblinpol

Reverse using slicing:  elpoep noillib fo noitan a ,aidnI

 

Splitting and Concatenating Strings

Let us directly look into an example to understand how to split a sentence into words:

str1 = "This is the string we will split into a list of words"
# By default, split function splits on space 
list_of_words = str1.split()
print(list_of_words)

Output:

['This', 'is', 'the', 'string', 'we', 'will', 'split', 'into', 'a', 'list', 'of', 'words']

 

Now, let us split on a delimiter, let’s say a comma:

str1 = "Literature, most generically, is any body of written works"
# Let us split on comma 
my_list = str1.split(',')
print(my_list)

Output:

['Literature', ' most generically', ' is any body of written works']

 

One of the simplest approaches is to use ‘+’ operator which can concatenate two strings:

str1 = 'Python'
str2 = 'Is Fun'
# Concatenate two strings
print(str1 + str2)
# More readable, concatenate 3 strings, str1, a space ' ' and str3
print(str1 + ' ' + str2)

Output:

PythonIs Fun

Python Is Fun

 

Few rules on concatenation:

 

Below code fails:

str1 = 'Python'
str2 = ' Is Fun'
str3 = ' Percent'
print(str1 + str2 + 100 + str3)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-0bf25e403437> in <module>
      2 str2 = 'Is Fun'
      3 str3 = 'Percent'
----> 4 print(str1 + str2 + 100 + str3)

TypeError: must be str, not int

Fix it by explicitly converting integer 100 to string:

str1 = 'Python'
str2 = ' Is Fun'
str3 = ' Percent'
print(str1 + str2 + str(100) + str3)

Output:

Python Is Fun 100 Percent

Concatenating a list of strings

We can concatenate strings using a list of strings easily

list_of_words = ['This', 'is', 'the', 'string', 'we', 'will', 'split', 'into', 'a', 'list', 'of', 'words']
# Start with empty string and use join function which is available on objects of type 'str' 
sentence = "".join(list_of_words)
print(sentence)
# Use a string with one space this time
sentence = " ".join(list_of_words)
print(sentence)
# Use a string with one hyphen/dash this time
sentence = "-".join(list_of_words)
print(sentence)
# You can observe that the string on which we call join is used to join the items in 'list_of_words'

Output:

Thisisthestringwewillsplitintoalistofwords
This is the string we will split into a list of words
This-is-the-string-we-will-split-into-a-list-of-words

 

Operations on String in Python

Python ‘str’ type has a lot of inbuilt functions

We have already seen str.join() and str.split() functions in last section. We will understand rest of the functions listed above.

# convert to upper case
print("python".upper())
# convert to lower case
print("PYTHON".lower())
# find index of 'th'
print('Python'.find('th'))
# replace substring '0' with '100'
print('Python Is Fun 0 Percent'.replace('0','100'))

Output:

PYTHON

python

2

Python Is Fun 100 Percent

 

With this, we come to an end of this strings in python blog. I hope all your doubts about strings in Python is clear now.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access. 

BROWSE COURSES