Python Programs on Strings
- Categories Python, Python Strings
Python Programs on Strings:
1. Write a Python program to check if a string is numeric.
Ans.
str = 'a123' #str = '123' try: i = float(str) except (ValueError, TypeError): print('\nNot numeric') print()
2. Write a Python program to check if lowercase letters exist in a string.
Ans.
str1 = 'A8238i823acdeOUEI' print(any(c.islower() for c in str1))
3. Write a Python program to count the number of characters (character frequency) in a string.
Ans.
def c(str1): dict = {} for n in str1: keys = dict.keys() if n in keys: dict[n] += 1 else: dict[n] = 1 return dict print(c(' simplycoding.in'))
4. Write a Python program to count the occurrences of each word in a given sentence.
Ans.
def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog.'))
5. Write a Python script that takes input from the user and displays that input back in upper and lower cases.
Ans.
user_input = input("What's your favourite language? ") print("My favourite language is ", user_input.upper()) print("My favourite language is ", user_input.lower())
6. Write a Python program to count and display the vowels of a given text.
Ans.
def vowel(text): vowels = "aeiuoAEIOU" print(len([letter for letter in text if letter in vowels])) print([letter for letter in text if letter in vowels]) vowel('Welcome To Simply Coding');
7. Write a Python program to remove spaces from a given string.
Ans.
def remove_spaces(str1): str1 = str1.replace(' ','') return str1 print(remove_spaces("Welcome To Simply Coding")) print(remove_spaces("a b c"))
8. Write a Python program to capitalize first and last letters of each word of a given string.
Ans.
def capitalize_first_last_letters(str1): str1 = result = str1.title() result = "" for word in str1.split(): result += word[:-1] + word[-1].upper() + " " return result[:-1] print(capitalize_first_last_letters("hello world")) print(capitalize_first_last_letters("Simply coding"))
You may also like
Python Strings
14 June, 2021
Solve any character pattern program in python
3 June, 2021
Solve any number patterns programs in python
3 June, 2021