Blog

Blog

How to Implement and Play with Strings in Python

When we Implement and 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 helpers 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.

Youtube banner Logo

Find out the type of a literal string: Function type() returns the 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 is used to point to a single character in a string 
  • Splicing can be used to pick a 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, and 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.

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 the ‘+’ 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:

The 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>
      2str2 ='Is Fun'
3str3 ='Percent'
----> 4print(str1 +str2 +100+str3)
TypeError: must be str, notint

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 the last section. We will understand the 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
2
Python Is Fun 100 Percent
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare

Subscribe to Newsletter

Stay ahead of the rapidly evolving world of technology with our news letters. Subscribe now!