Hello reader. Welcome to our blog and a new chapter in our Python tutorial series, “Learn Python with me”. This chapter is the continuation of the previous chapter, and therefore we will discuss the Python Strings once again and for the last time, probably in this tutorial series. We will discuss here in this chapter a few topics such as Working with characters, Sorting and Searching the strings, how to find the number of characters or words in Python String, Inserting SubString into any Main String.
Find the link to all our Python Chapters: Learn Python
How to work with characters in Python?
A group of characters are called a String. We know you know that. However, we have seen mostly the concepts that deal with the whole Python Strings and not characters though we have discussed this concept in topics like Slicing in Python in our earlier chapters. But do not worry; we will discuss once again for your reference so that you can bookmark this link specifically to refer to the concepts of characters again and again.
As a programmer of Python, if you want to deal with the characters, you must understand that you will deal with the individual elements/characters of the string through slicing or indexing.
Let us look at an example to understand the operations you can perform on individual characters.
#Python program to work with characters
string1=input("Enter any character: ")
a=string1[0] #takes only 0th character
#Let us perform some tests
if a.isalnum():
print("It is either numeric or alphabetic")
if a.isalpha():
print('But you know it is alphabetic')
if a.isupper():
print("It is also a capital letter")
else:
print("It is a lowercase letter buddy")
else:
print("It is a numeric digit")
elif a.isspace():
print("Why did you enter space?")
else:
print("I am guessing it to be a special character")
Output
Enter any character: !
I am guessing it to be a special character
How to sort Python string in an array?
You can sort the strings in Python using the sorted() function and sort() method. We use the sort() method to sort any string in the same Python Array, and the sorted() function can be used when you want to declare a new array and add the sorted values in the new array.
#sort python strings in an array
#declare an empty array
string1 = []
#define the number of strings
num=int(input('How many strings bro?'))
#add strings to string1 array
for item in range(num):
print("Enter desired string: ",end='')
string1.append(input())
print("Declared string: ",string1)
string1.sort() #sort() can be used in the same array
print("After sorting using Sort() method: ",string1)
#let us sort the array
string2=sorted(string1) #sorted can be used in new array
#display the sorted array
print("The sorted list is: ")
for item in string2:
print(item)
Output
How many strings bro?3
Enter desired string: Howrah
Enter desired string: Delhi
Enter desired string: Chennai
Declared string: ['Howrah', 'Delhi', 'Chennai']
After sorting using Sort() method: ['Chennai', 'Delhi', 'Howrah']
The sorted list is:
Chennai
Delhi
Howrah
How to search Python string in an array?
We can search strings in an array by using a linear search technique or sequential search. You can do this by comparing a string with every other string in the array. You can use the for loop iteration to achieve this, and please refer to the logic here below for the same:
#logic
for item in range(len(string1):
if word==string1[item]:
Let us look at an example now.
#program to search string in an array
#declare the empty string
string1=[]
#define the number of strings
num=int(input("How many strings?: "))
#add strings to string1 array
for item in range(num):
print("Enter the string: ",end="")
string1.append(input())
#word you want to search
word=input("Enter the word you want to search: ")
#search logic
check=False
for item in range(len(string1)):
if word==string1[item]:
print("Yes the string is present at location: ",item+1)
check=True
if check==False:
print("The word is not present")
Output
How many strings?: 3
Enter the string: Delhi
Enter the string: Hyderabad
Enter the string: Chennai
Enter the word you want to search: Chennai
Yes the string is present at location: 3
How to find the number of Words and Characters?
In Python, you can use the len() function to find the number of characters in a string. You can also use certain logic to find the number of words in a sentence. Let us look at the examples now.
Program to find the number of characters in a string
#the program to find number of characters in a string
string1=input("Enter any string: ")
print("The declared string has",len(string1),"characters")
Output
Enter any string: pycharm
The declared string has 7 characters
Program to find the number of words in a sentence
#program to find the number of words in a sentence
string1=input("Enter a sentence: ")
#check if string is empty
if(len(string1)==0):
print("This is empty string")
#if string is not empty, execute logic to count
else:
string2=string1.split()
a=0
for i in string2:
a=a+1
print("There are",a,"words in declared string")
Output
Enter a sentence: This is cool
There are 3 words in declared string
How to add sub string to any main Python string?
There are several ways to add a substring to the main string in Python. And we will discuss the easiest way to do this through the concept of slicing. Please find below the detailed steps on how we will create the program for the same:
- We should first create two strings to store the main string and substring. In our program, we added the input function for these strings to obtain the input from the keyboard.
- We should then create another integer variable and add an input function to obtain the position number from the keyboard.
- Since the exact location of the individual characters of the string is positioned by index location numbers, add logic for the same. In our program, it is (num-=1).
- Using the concepts of slicing, add the characters of the string from the beginning till index position num, then append the substring using concatenation, and finally add the characters of the main string from index position num till the end. If necessary, also add a space after the substring using concatenation. Finally, save the same to another result variable.
- When you now display the result variable, the final desired output is printed as intended.
#python program to add sub string to any main string
#declare main string
string1=input("Enter main string: ")
#declare sub string
string2=input("Enter substring: ")
#display the main string and sub string
print("The original string ",string1)
print("The substring: ",string2)
#request position number from keyboard
num=int(input("Enter position num: "))
#index location = position number - 1
num-=1
#result logic using slicing
result=string1[:num]+string2+" "+string1[num:]
#print result
print(result)
Output
Enter main string: It is winter
Enter substring: cool
The original string It is winter
The substring: cool
Enter position num: 7
It is cool winter