Python String Programs, Exercises, Examples

Python string is a sequence of characters, such as “hello”. They can be used to represent text in a programming language. Strings can be created by enclosing a sequence of characters between double quotes, such as “hello”, or by using the str() function.

1). Write a Python program to get a string made of the first and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string

2). Python string program that takes a list of strings and returns the length of the longest string.

3). Python string program to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).

4). Python string program to reverse a string if it’s length is a multiple of 4.

5). Python string program to count occurrences of a substring in a string.

6). Python string program to test whether a passed letter is a vowel or consonant.

7). Find the longest and smallest word in the input string.

8). Print most simultaneously repeated characters in the input string.

9). Write a Python program to calculate the length of a string with loop logic.

10). Write a Python program to replace the second occurrence of any char with the special character $.
Input = “Programming”
Output = “Prog$am$in$”

11). Write a python program to get to swap the last character of a given string.
Input = “SqaTool”
Output = “IqaTooS”

12). Write a python program to exchange the first and last character of each word from the given string.
Input = “Its Online Learning”
Output = “stI enlino gearninL”

13). Write a python to count vowels from each word in the given string show as dictionary output.
Input = “We are Learning Python Codding”
output = {“We” : 1, “are” : 2, “Learning” : 3, “Python”:1, “Codding”}

14). Write a python to repeat vowels 3 times and consonants 2 times.
Input = “Sqa Tools Learning”
Ouput = “SSqqaaa TToooooollss LLeeeaaarrnniiinngg”

15). Write a python program to re-arrange the string.
Input = “Cricket Plays Virat”
Output = “Virat Plays Cricket”

16). Write a python program to get all the digits from the given string.
Input = “””
Sinak’s 1112 aim is to 1773 create a new generation of people who
understand 444 that an organization’s 5324 success or failure is
based on 555 leadership excellence and not managerial
acumen
“””
Output = [1112, 5324, 1773, 5324, 555]

17). Write a python program to replace the words “Java” with “Python” in the given string.
Input = “JAVA is the Best Programming Language in the Market”
Output = “Python is the Best Programming Language in the Market”

18). Write a Python program to get all the palindrome words from the string.
Input = “Python efe language aakaa hellolleh”
output = [“efe”, “aakaa”, “hellolleh”]

19). Write a Python program to create a string with a given list of words.
Input = [“There”, “are”, “Many”, “Programming”, “Language”]
Output = There are many programming languages.

20). Write a Python program to remove duplicate words from the string.
Input = “John jany sabi row john sabi”
output = “John jany sabi row”

21). Write a Python to remove unwanted characters from the given string.
Input = “Prog^ra*m#ming”
Output = “Programming”

Input = “Py(th)#@&on Pro$*#gram”
Output = “PythonProgram”

22). Write a Python program to find the longest capital letter word from the string.
Input = “Learning PYTHON programming is FUN”
Output = “PYTHON”

23). Write a Python program to get common words from strings.
Input String1 = “Very Good Morning, How are You”
Input String1 = “You are a Good student, keep it up”
Output = “You Good are”

24). Write a Python program to find the smallest and largest word in a given string.
Input = “Learning is a part of life and we strive”
Output = “a”, “Learning”

25). Check whether the given string is a palindrome (similar) or not.
Input= sqatoolssqatools
Output= Given string is not a palindrome

26). Write a program using python to reverse the words in a string.
Input= sqatools python
Output= slootaqs

27). Write a program to calculate the length of a string.
Input= “python”
Output = 6

28). Write a program to calculate the frequency of each character in a string.
Input = “sqatools”
Output = {‘s’:2, ‘q’:1, ‘a’: 1, ‘t’:1,‘o’:2, ‘l’:1, ‘s’:1}

29). Write a program to combine two strings into one.
Input: 
A = ’abc’
B = ’def’
Output = abcdef

30). Write a program to print characters at even places in a string.
Input = ‘sqatools’
Output = saol

31). Write a program to check if a string has a number or not.
Input = ‘python1’
Output = ‘Given string have a number’

32). Write a python program to count the number of vowels in a string.
Input= ‘I am learning python’
Output= 6

33). Write a python program to count the number of consonants in a string.
Input= ‘sqltools’
Output= 6

34). Write a program to print characters at odd places in a string.
Input = ‘abcdefg’
Output = ‘bdf’

35). Write a program to remove all duplicate characters from a given string in python.
Input = ‘sqatools’
Output = ‘sqatol’

36). Write a program to check if a string has a special character or not
Input = ‘python$$#sqatools’
Output =  ‘Given string has special characters

37). Write a program to exchange the first and last letters of the string
Input = We are learning python
Output = ne are learning pythoW

38). Write a program to convert all the characters in a string to Upper Case.
Input = ‘I live in pune’
Output = ‘I LIVE IN PUNE’

39). Write a program to remove a new line from a string using python.
Input = ‘objectorientedprogramming\n’
Output = ‘Objectorientedprogramming’

40). Write a python program to split and join a string
Input =‘Hello world’
Output = [‘Hello’, ‘world’]
                 Hello-world

41). Write a program to print floating numbers up to 3 decimal places and convert it to string.
Input = 2.14652
Output= 2.146

42). Write a program to convert numeric words to numbers.
Input = ‘five four three two one’
Output = 54321

43). Write a python program to find the location of a word in a string
Input Word = ‘problems’
Input string = ‘ I am solving problems based on strings’
Output = 4

44). Write a program to count occurrences of a word in a string.

Word = ‘food’
Input str = ‘ I want to eat fast food’
Occurrences output= 1

Word = ‘are’
Input str = “We are learning Python, wow are you”
Occurrences output = 2 

45). Write a python program to find the least frequent character in a string.
Input =  ‘abcdabdggfhf’
Output = ‘c’

46). Find the words greater than the given length.
Ex length = 3
Input = ‘We are learning python’
Output – ‘learning python’

47). Write a program to get the first 4 characters of a string.
Input = ‘Sqatools’
Output = ‘sqat’

48). Write a Python program to get a string made of the first 2 and the last 2 chars from a given string.
Input = ‘Sqatools’
Output = ‘Sqls’ 

49). Write a python program to print the mirror image of the string.
Input = ‘Python’
Output = ‘nohtyp 

50). Write a python program to split strings on vowels
Input = ‘qwerty’
Output = ‘qw rty’

51). Write a python program to replace multiple words with certain words.
Input = “I’m learning python at Sqatools”
Replace python with SQA  and sqatools with TOOLS 
Output = “I’m learning SQA at TOOLS “

52). Write a python program to replace different characters in the string at once.
Input = ‘Sqatool python’
Replace a with 1,
Replace t with 2,
Replace o with 3
Output = ‘sq1233l py2h3n”

53). Write a python program to remove empty spaces from a list of strings.
Input = [‘Python’, ‘ ‘, ‘ ‘, ‘sqatools’]
Output = [‘Python’, ‘sqatools’] 

54).  Write a python program to remove punctuations from a string
Input = ‘Sqatools : is best, for python’
Output = ‘Sqatools is best for python’

55).  Write a python program to find duplicate characters in a string
Input = “hello world”
Output = ‘lo’

56).  Write a python program to check whether the string is a subset of another string or not
Input str1 = “iamlearningpythonatsqatools”
str = ‘pystlmi’
Output = True

57). Write a python program to sort a string
Input = ‘xyabkmp’
Output = ‘abkmpxy’

58). Write a python program to generate a random binary string of a given length.
Input = 8
Output = 10001001

59). Write a python program to check if the substring is present in the string or not
Input string= ‘I live in Pune’
Substring= ‘I live ‘
Output = ‘Yes

60). Write a program to find all substring frequencies in a string.
Input str1 = “abab” 
Output = {‘a’: 2, ‘ab’: 2, ‘aba’: 1,‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}  

61). Write a python program to print the index of the character in a string.
Input = ‘Sqatools’
Output = ‘The index of q is 1’

62). Write a program to strip spaces from a string.
Input = ‘    sqaltoolspythonfun     ‘ 
Output = ‘ sqaltoolspythonfun’

63). Write a program to check whether a string contains all letters of the alphabet or not.
Input = ‘abcdgjksoug’
Output = False

64). Write a python program to convert a string into a list of words.
Input = ‘learning python is fun’
Output = [learning, python, is, fun] 

65). Write a python program to swap commas and dots in a string.
Input = sqa,tools.python
Output = sqa.tools,python

66). Write a python program to count and display the vowels in a string
Input = ‘welcome to Sqatools’
Output = 7

67). Write a Python program to split a string on the last occurrence of the delimiter. 
Input = ‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’
Output = [‘l,e,a,r,n,I,n,g,p,y,t,h,o ‘ ,’n’]

68). Write a Python program to find the first repeated word in a given string. 
Input = ‘ab bc ca ab bd’
Output = ‘ab’

69). Write a program to find the second most repeated word in a given string using python.
Input = ‘ab bc ac ab bd ac nk hj ac’
Output = (‘ab’, 2)

70). Write a Python program to remove spaces from a given string.
Input = ‘python at sqatools’
Output = ‘pythonatsqatools’

71). Write a Python program to capitalize the first and last letters of each word of a given string.
Input = ‘this is my first program’
Output = ‘ThiS IS MY FirsT PrograM’

72). Write a Python program to calculate the sum of digits of a given string.
Input = ’12sqatools78′
Output = 18

73). Write a Python program to remove zeros from an IP address. 
Input = 289.03.02.054
Output = 289.3.2.54

74). Write a program to find the maximum length of consecutive 0’s in a given binary string using python.
Input = 10001100000111
Output = 5 

75). Write a program to remove all consecutive duplicates of a given string using python.
Input = ‘xxxxyy’
Output = ‘xy’

76). Write a program to create strings from a given string. Create a string that consists of multi-time occurring characters in the said string using python.
Input = “aabbcceffgh”
Output = ‘abcf’

77). Write a Python program to create a string from two given strings combining uncommon characters of the said strings.  

Input string :
s1 = ‘abcdefg’
s2 = ‘xyzabcd’
Output string : ‘efgxyz’

78). Write a Python code to remove all characters except the given character in a string. 
Input = “Sqatools python”
Remove all characters except S
Output = ‘S’

79). Write a program to count all the Uppercase, Lowercase, special character and numeric values in a given string using python.
Input = ‘@SqaTools.lin’
Output:
Special characters: 1
Uppercase characters: 2
Lowercase characters: 8

80). Write a Python program to count a number of non-empty substrings of a given string.
Input a string = ‘sqatools12’
Number of substrings = 55

81). Write a program to remove unwanted characters from a given string using python.
Input = ‘sqa****too^^{ls’
Output = ‘Sqatools’

82). Write a program to find the string similarity between two given strings using python.
Input
Str1 = ‘Learning is fun in Sqatools’
Str2 = ‘Sqatools Online Learning Platform’

Output :
Similarity : 0.4

83). Write a program to extract numbers from a given string using python.
Input = ‘python 456 self learning 89’
Output = [456, 89]

84). Write a program to split a given multiline string into a list of lines using python.
Input =”’This string Contains
Multiple
Lines”’
Output = [‘This string Contains’, ‘Multiple’, ‘Lines’]

85). Write a program to add two strings as they are numbers using python.
Input :
a=’3′, b=’7′
Output  = ’10’

86). Write a program to extract name from a given email address using python.
Input = ‘student1@gmail.com’
Output = ‘student’

87). Write a  program that counts the number of leap years within the range of years using python. The range of years should be accepted as a string. 

(“1981-2001)  =  Total leap year 5

88). Write a program to insert space before every capital letter appears in a given word using python. 
Input = ‘SqaTools pyThon’
Output = ‘ Sqa Tools py Thon’ 

89). Write a program to uppercase half string using python.
Input = ‘banana’
Output = ‘banANA’

90). Write a program to split and join a string using “-“.
Input = ‘Sqatools is best’
Output = ‘Sqatools-is-best’

91). Write a python program to find permutations of a given string using in built function.
Input  = ‘CDE’
Output = [‘CDE’, ‘CED’ ‘EDC’, ‘ECD’, ‘DCE’, ‘DEC’]

92). Write a program to avoid spaces in string and get the total length
Input = ‘sqatools is best for learning python’
Output = 31

93). Write a program to accept a string that contains only vowels
Input = ‘python’
Output- ‘not accepted’

Input = ‘aaieou’
Output = ‘accepted’

94). Write a program to remove the kth element from the string
K=2
Input = ‘sqatools’
Output = ‘sqtools’

95). Write a program to check if a given string is binary or not.
Hint: Binary numbers only contain 0 or 1.

Input = ‘01011100’
Output = yes

Input = ‘sqatools 100’
Output = ‘No’

96). Write a program to add ‘ing’ at the end of the string using python.
Input = ‘xyz’
Output = ‘xyzing’

97). Write a program to add ly at the end of the string if the given string ends with ing.
Input = ‘winning’
Output = ‘winningly’

98). Write a program to reverse words in a string using python.
Input = ‘string problems’
Output = ‘problems string’

99). Write a program to print the index of each character in a string.
Input =  ‘sqatools’
Output :
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

100). Write a program to find the first repeated character in a string and its index.
Input = ‘sqatools’
Output = (s,0)

101). Write a program to swap cases of a given string using python.
Input = ‘Learning Python’
Output = ‘lEARNING pYTHON’

102). Write a program to remove repeated characters in a string and replace it with a single letter using python.
Input = ‘aabbccdd’
Output = ‘cabd’

103). Write a program to print a string 3 times using python.
Input = ‘sqatools’
Output = ‘sqatoolssqatoolssqatools’

104). Write a program to print each character on a new line using python.
Input = ‘python’
Output:
p
y
t
h
o
n

105). Write a program to get all the email id’s from given string using python.
Input str = “”” We have some employee whos john@gmail.com email id’s are randomly distributed jay@lic.com we want to get hari@facebook.com all the email mery@hotmail.com id’s from this given string.”””
Output = [‘john@gmail.com’, ‘ jay@lic.com’, ‘hari@facebook.com’, ‘mery@hotmail.com’ ]

106). Write a program to get a list of all the mobile numbers from the given string using python.
Input str = “”” We have 2233 some employee 8988858683 whos 3455 mobile numbers are randomly distributed 2312245566 we want 453452 to get 4532892234 all the mobile numbers 9999234355  from this given string.”””
Output = [‘8988858683’, ‘2312245566’, ‘4532892234’, ‘9999234355’]

Get a list of mobile numbers from the string

In this program, we will take a string as input and get a list of mobile numbers from the given string.

Steps to solve the program
  1. Take a list as input.
  2. Convert the string into a list using split() and create an empty list.
  3. Use for loop to iterate over every word in the list.
  4. If the length of the word is 10 and that word contains all numbers then add that word to the empty list.
  5. Print the output.

Output :

get all the email id’s from given string

Get all the email id’s from the given string

In this program, we will take a string as input and get all the email id’s from the given string.

Steps to solve program
  1. Take a string as input.
  2. Convert the string into a list using split() and create an empty list.
  3. Using for loop iterate over each word in the string.
  4. If the character in the word contains “@” add that word to the empty string.
  5. Print the output.

Output :

print each character on a new line

get a list of all the mobile numbers from the given string

Find the first repeated character and its index.

In this program, we will take a string as input and find the first repeated character in a string and its index.

Steps to solve the program
  1. Take a string as input.
  2. Use for loop with range() function to find the first repeated character.
  3. Find the index of that character using Index().
  4. After finding the first character break the loop.
  5. Print the output.

Output :

index of each character in a string.

swap cases of a given string using python.

Print the index of each character in a string.

In this program, we will take a string as input and print the index of each character in a string.

Steps to solve the program
  1. Take a string as input.
  2. Use for loop to iterate over each character of the string.
  3. Find the index of the character using Index().
  4. Print the output.

Output :

reverse words in a string using python.

find the first repeated character in a string and its index.