String Programs in Python
1.Write a program to reverse a string.
def reverse_string(s):
return s[::-1]
string = "hello"
print(reverse_string(string))
2. Write a program to check if a string is a palindrome.
def is_palindrome(s):
return s == s[::-1]
string
= "madam"
print(is_palindrome(string))
3.Write a program to count the number of vowels and consonants in a
string.
def count_vowels_consonants(s):
vowels = "aeiouAEIOU"
v_count = c_count = 0
for char in s:
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count
string = "hello"
vowels, consonants = count_vowels_consonants(string)
print(f"Vowels: {vowels}, Consonants: {consonants}")
4.
Write a program to remove duplicate characters from a string.
def remove_duplicates(s):
result = ""
for char in s:
if char not in result:
result += char
return result
string = "programming"
print(remove_duplicates(string))
5.
Write a program to count the frequency of each character in a
string.
from collections import Counter
def
char_frequency(s):
return dict(Counter(s))
string = "hello"
print(char_frequency(string))
6. Write a program to check if two strings are anagrams.
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
string1 = "listen"
string2 = "silent"
print(are_anagrams(string1, string2))
7.
Write a program to find the longest word in a sentence.
def longest_word(sentence):
words = sentence.split()
return max(words, key=len)
sentence = "I love programming in Python"
print(longest_word(sentence))
8.
Write a program to capitalize the first and last character of each
word in a string.
def capitalize_first_last(s):
words = s.split()
result = []
for word in words:
if len(word) > 1:
word = word[0].upper() + word[1:-1] + word[-1].upper()
else:
word = word.upper()
result.append(word)
return " ".join(result)
string = "hello world"
print(capitalize_first_last(string))
9.
Write a program to replace all occurrences of a substring in a
string.
def replace_substring(s, old, new):
return s.replace(old, new)
string = "hello world"
print(replace_substring(string, "world", "there"))
10.
Write a program to find all possible substrings of a string.
def all_substrings(s):
substrings = []
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
substrings.append(s[i:j])
return substrings
string = "abc"
print(all_substrings(string))
Comments
Post a Comment