Python Scripting (9 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (45 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (304 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

How to Implement and Play with Strings in Python

Published on Sep 19,2019 37 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

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?
  • How to use strings, indexing, and slicing?
  • Splitting and concatenating strings
  • Operations on string in Python

 

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

  • Indexing is used to point to a single character in a string 

  • Splicing can be used to pick substring or a sequence of characters according to splice rules

  • Indexing uses notation: str[index] where index is a number from 0 to len(str) – 1

  • Slicing uses notation: str[start : stop : step]

    • start: the beginning index of the slice, it will include the element at this index unless it is the same as stop, defaults to 0, i.e. the first index. If it’s negative, it means to start n items from the end.

    • stop: the ending index of the slice, it does not include the element at this index, defaults to the length of the sequence being sliced, that is, up to and including the end.

    • step: the amount by which the index increases, defaults to 1. If it’s negative, you’re slicing over the iterable in reverse.

  • Slicing works over a list as well or for that matter any sequence. In this blog, we are looking at strings alone.

Strings-in-python

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

  • Splitting 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']

 

  • Concatenating Strings

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:

  • Concatenation works only on ‘str’ objects
  • If objects of other types are included, Python will throw error.
  • Unlike other languages, Python will not automatically typecast other types to string
  • Python requires explicit typecast to string using str() function

 

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

  • join() function is available on any object of type ‘str’
  • join() accepts a list of strings only, if it contains non-string items, python will throw an error
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

  • str.upper()
  • str.lower()
  • str.find()
  • str.replace()
  • str.split()
  • str.join()
  • Many more

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. 

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.