Python sort strings

We can sort a group of strings into alphabetical order using sorted() function. The sort() method is used in the following way:

str.sort()

Here, 'str' represents an array that contains a group of strings. When sort() method is used, it will sort the original array, i.e. 'str'. So, the original order of strings will be lost and we will have only one sorted array. To retain the original array even after sorting, we can use sorted() function as:

str1 = sorted(str)

sort string example:

A Python program to sort a group of strings into alphabetical order.

CopiedCopy Code

str = [] 
n = int(input('How many strings?')) 
for i in range(n): 
print('Enter string:', end='') 
str.append(input()) 
str1 = sorted(str) 
print('Sorted list:') 
for i in str1: 
  print(i)

searching in the strings

The easiest way to search for a string in a group of 'n' strings is by using sequential search or linear search technique. This is done by comparing the searching string 's' with every string in the group. For this purpose, we can use a for loop that iterates from 0th to n-1th string in the group. By comparing the searching string 's' with every one of these strings, we can decide whether 's' is available in the group or not. The logic looks something like this:

CopiedCopy Code

for i in range(len(str)): 
   if s==str[i]:
str = [] 
n = int(input('How many strings?')) 
for i in range(n): 
print('Enter string:', end='') 
str.append(input()) 
s = input('Enter string to search:') 
flag = False 
for i in range(len(str)): 
   if s==str[i]: 
print('Found at:', i+1)
flag=True 
if flag==False: 
print('Not found')