[go: up one dir, main page]

0% found this document useful (0 votes)
23 views3 pages

String Op

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 3

Write a Python program to compute following operations on strings:

1. Display word with the longest length


2. To check whether given string is a palindrome
3. To display index of first occurrence of substring
4. To count occurrence of each word in given string
5. To count frequency of occurrence of particular character in a given string.

sentence=input("Enter the string: ")


str1=sentence.lower()
split_value=[]
temp=""
for char in str1:
if char==" " and temp!="":
split_value.append(temp)
temp= ""
else:
temp+=char
#for last word:
if temp:
split_value.append(temp)
print(split_value)

def longest_length(split_value):
max1=len(split_value)
a=split_value[0]

#for loop to transverse in the list


for i in split_value:
if(len(i)>max1):
max1=len(i)
a=i
print("The word with the longest length is:",a,"and length is",max1)
longest_length(split_value)

def word_count(str):
counts = dict()
words = split_value

for word in words:


if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print(word_count(str1))
character=input("Enter the character: ")

def countOccurrences(sentence, character):


# Counter variable
counter = 0
for char in sentence:
if char == character:
counter += 1
return counter
print("The character",character," has occured", countOccurrences(str1, character),"times in the
string.")

def Substring_index():
count1=0
count2=0
str2=str(input("Enter the required string\n"))
for i in str2:
count1+=1 #Calculating length of initial string
key=str(input("Enter the substring\n"))
for j in key:
count2+=1 #Calculating length of substring/key
var1=0
for x in range(count1): #Iterate through length of original string
b=str2[var1:count2] #Slice every part of original string in pieces of length of substring
var1+=1
count2+=1
if(b==key): #Compare with key
print(x) #Return index
break
Substring_index()

def is_palindrome(s):
return s==s[::-1]

s=input("Enter a word: ")


ans=is_palindrome(s)

if ans:
print("Yes the given word is a palindrome.")
else:
print("The given string is not a palindrome.")

Output:
Enter the string: Mary had a little lamb
['mary', 'had', 'a', 'little', 'lamb']
The word with the longest length is: little and length is 6
{'mary': 1, 'had': 1, 'a': 1, 'little': 1, 'lamb': 1}
Enter the character: t
The character t has occured 2 times in the string.
Enter the required string
rainbow has seven colors
Enter the substring
rainbow
0
Enter a word: malayalam
Yes the given word is a palindrome.

Process finished with exit code 0

You might also like