String - Scenario Based Python Programs

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

PYTHON STRING - SCENARIO BASED PROGRAMS

______________________________________________________________________________

1.Word Count:

Write a program that counts the occurrences of each word in a given text string.

def word_count(text):
words = text.split()
word_freq = {}
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq

def main():
text = input("Enter the text: ")
word_frequency = word_count(text)
print("Word Frequency:")
for word, count in word_frequency.items():
print(f"{word}: {count}")

if __name__ == "__main__":
main()

______________________________________________________________________________
2. Palindrome Check:

Create a program to check if a given string is a palindrome.

def is_palindrome(s):
s = s.lower()
s = ''.join(char for char in s if char.isalnum())
return s == s[::-1]

def main():
string = input("Enter a string: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

if __name__ == "__main__":
main()
______________________________________________________________________________

3. Anagram Check:

Write a program to check if two strings are anagrams of each other.

def is_anagram(s1, s2):


s1 = s1.lower().replace(" ", "")
s2 = s2.lower().replace(" ", "")
return sorted(s1) == sorted(s2)

def main():
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
if is_anagram(string1, string2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
if __name__ == "__main__":
main()
______________________________________________________________________________

4. Reverse String:

Develop a program to reverse a given string.

def reverse_string(s):
return s[::-1]

def main():
string = input("Enter a string: ")
reversed_string = reverse_string(string)
print("Reversed string:", reversed_string)

if __name__ == "__main__":
main()
______________________________________________________________________________
5. Count Vowels and Consonants:
Create a program that counts the number of vowels and consonants in a given string.
def count_vowels_consonants(s):
vowels = 'aeiou'
vowels_count = sum(1 for char in s.lower() if char in vowels)
consonants_count = sum(1 for char in s.lower() if char.isalpha() and char not in vowels)
return vowels_count, consonants_count

def main():
string = input("Enter a string: ")
vowels, consonants = count_vowels_consonants(string)
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")

if __name__ == "__main__":
main()
______________________________________________________________________________

You might also like