w3resource

Python Data Type: String - Exercises, Practice, Solution


Python String [113 exercises with solution]


Python has a built-in string class named "str" with many useful features. String literals can be enclosed by either single or double, although single quotes are more commonly used.

You may read our Python string tutorial before solving the following exercises.

[An editor is available at the bottom of the page to write and execute the scripts.  Go to the editor]

1. Calculate string length.

Write a Python program to calculate the length of a string.
Click me to see the sample solution

2. Count character frequency in a string.

Write a Python program to count the number of characters (character frequency) in a string.
Sample String : google.com'
Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
Click me to see the sample solution

3. Get string of first and last 2 chars.

Write a Python program to get a string made of the first 2 and last 2 characters of a given string. If the string length is less than 2, return the empty string instead.
Sample String : 'w3resource'
Expected Result : 'w3ce'
Sample String : 'w3'
Expected Result : 'w3w3'
Sample String : ' w'
Expected Result : Empty String
Click me to see the sample solution

4. Replace first char occurrences with $.

Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t'
Click me to see the sample solution

5. Swap first 2 chars of 2 strings.

Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.
Sample String : 'abc', 'xyz'
Expected Result : 'xyc abz'
Click me to see the sample solution

6. Add ing or ly to a string.

Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing', add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly'
Click me to see the sample solution

7. Replace 'not'...'poor' with 'good'.

Write a Python program to find the first appearance of the substrings 'not' and 'poor' in a given string. If 'not' follows 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string.
Sample String : 'The lyrics is not that poor!'
'The lyrics is poor!'
Expected Result : 'The lyrics is good!'
'The lyrics is poor!'
Click me to see the sample solution

8. Find longest word in a list.

Write a Python function that takes a list of words and return the longest word and the length of the longest one.
Sample Output:
Longest word: Exercises
Length of the longest word: 9
Click me to see the sample solution

9. Remove nth character from a string.

Write a Python program to remove the nth index character from a nonempty string.
Click me to see the sample solution

10. Swap first and last chars of a string.

Write a Python program to change a given string to a newly string where the first and last chars have been exchanged.
Click me to see the sample solution

11. Remove odd index chars from a string.

Write a Python program to remove characters that have odd index values in a given string.
Click me to see the sample solution

12. Count word occurrences in a sentence.

Write a Python program to count the occurrences of each word in a given sentence.
Click me to see the sample solution

13. Display input in upper and lower case.

Write a Python script that takes input from the user and displays that input back in upper and lower cases.
Click me to see the sample solution

14. Sort distinct words in comma-separated input.

Write a Python program that accepts a comma-separated sequence of words as input and prints the distinct words in sorted form (alphanumerically).
Sample Words : red, white, black, red, green, black
Expected Result : black, green, red, white,red
Click me to see the sample solution

15. Wrap word(s) in HTML tags.

Write a Python function to create an HTML string with tags around the word(s).
Sample function and result :
add_tags('i', 'Python') -> '<i>Python</i>'
add_tags('b', 'Python Tutorial') -> '<b>Python Tutorial </b>'
Click me to see the sample solution

16. Insert string into middle of another.

Write a Python function to insert a string in the middle of a string.
Sample function and result :
insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]]
insert_sting_middle('{{}}', 'PHP') -> {{PHP}}
Click me to see the sample solution

17. Repeat last 2 chars of a string 4 times.

Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).
Sample function and result :
insert_end('Python') -> onononon
insert_end('Exercises') -> eseseses
Click me to see the sample solution

18. Get first 3 chars of a string.

Write a Python function to get a string made of the first three characters of a specified string. If the length of the string is less than 3, return the original string.
Sample function and result :
first_three('ipy') -> ipy
first_three('python') -> pyt
Click me to see the sample solution

19. Get substring before a specific character.

Write a Python program to get the last part of a string before a specified character.
https://www.w3resource.com/python-exercises
https://www.w3resource.com/python
Click me to see the sample solution

20. Reverse string if length is a multiple of 4.

Write a Python function to reverse a string if its length is a multiple of 4.
Click me to see the sample solution

21. Uppercase string if 2+ uppercase chars in first 4.

Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters.
Click me to see the sample solution

22. Sort string lexicographically.

Write a Python program to sort a string lexicographically.
Click me to see the sample solution

23. Remove newline from a string.

Write a Python program to remove a newline in Python.
Click me to see the sample solution

24. Check if string starts with specified chars.

Write a Python program to check whether a string starts with specified characters.
Click me to see the sample solution

25. Implement Caesar cipher encryption.

Write a Python program to create a Caesar encryption.

Note : In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.

Click me to see the sample solution

26. Display formatted text (width=50).

Write a Python program to display formatted text (width=50) as output.
Click me to see the sample solution

27. Remove indentation from text.

Write a Python program to remove existing indentation from all of the lines in a given text.
Click me to see the sample solution

28. Add prefix to each line of text.

Write a Python program to add prefix text to all of the lines in a string.
Click me to see the sample solution

29. Set first line indentation.

Write a Python program to set the indentation of the first line.
Click me to see the sample solution

30. Print numbers with 2 decimal places.

Write a Python program to print the following numbers up to 2 decimal places.
Click me to see the sample solution

31. Print numbers with sign (2 decimals).

Write a Python program to print the following numbers up to 2 decimal places with a sign.
Click me to see the sample solution

32. Print numbers without decimal places.

Write a Python program to print the following positive and negative numbers with no decimal places.
Click me to see the sample solution

33. Print integers with left-padded zeros.

Write a Python program to print the following integers with zeros to the left of the specified width.
Click me to see the sample solution

34. Print integers with * right-padded.

Write a Python program to print the following integers with '*' to the right of the specified width.
Click me to see the sample solution

35. Display number with comma separator.

Write a Python program to display a number with a comma separator.
Click me to see the sample solution

36. Format number as percentage.

Write a Python program to format a number with a percentage.
Click me to see the sample solution

37. Align number left, right, center (width=10).

Write a Python program to display a number in left, right, and center aligned with a width of 10.
Click me to see the sample solution

38. Count substring occurrences in string.

Write a Python program to count occurrences of a substring in a string.
Click me to see the sample solution

39. Reverse a string.

Write a Python program to reverse a string.
Click me to see the sample solution

40. Reverse words in a string.

Write a Python program to reverse words in a string.
Click me to see the sample solution

41. Strip specific characters from string.

Write a Python program to strip a set of characters from a string.
Click me to see the sample solution

42. Count repeated characters in string.

Write a Python program to count repeated characters in a string.
Sample string: 'thequickbrownfoxjumpsoverthelazydog'
Expected output :
o 4
e 3
u 2
h 2
r 2
t 2
Click me to see the sample solution

43. Print area (rectangle) and volume (cylinder).

Write a Python program to print the square and cube symbols in the area of a rectangle and the volume of a cylinder.
Sample output:
The area of the rectangle is 1256.66cm2
The volume of the cylinder is 1254.725cm3
Click me to see the sample solution

44. Find character indices in string.

Write a Python program to print the index of a character in a string.
Sample string: w3resource
Expected output:
Current character w position at 0
Current character 3 position at 1
Current character r position at 2
- - - - - - - - - - - - - - - - - - - - - - - - -
Current character c position at 8
Current character e position at 9
Click me to see the sample solution

45. Check if string has all alphabet letters.

Write a Python program to check whether a string contains all letters of the alphabet.
Click me to see the sample solution

46. Convert string to list of words.

Write a Python program to convert a given string into a list of words.
Sample Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
Click me to see the sample solution

47. Lowercase first n characters of string.

Write a Python program to lowercase the first n characters in a string.
Click me to see the sample solution

48. Swap commas and dots in a string.

Write a Python program to swap commas and dots in a string.
Sample string: "32.054,23"
Expected Output: "32,054.23"
Click me to see the sample solution

49. Count and display vowels in text.

Write a Python program to count and display vowels in text.
Click me to see the sample solution

50. Split string on last delimiter occurrence.

Write a Python program to split a string on the last occurrence of the delimiter.
Click me to see the sample solution

51. Find first non-repeating character.

Write a Python program to find the first non-repeating character in a given string.
Click me to see the sample solution

52. Permutations with repetition in string.

Write a Python program to print all permutations with a given repetition number of characters of a given string.
Click me to see the sample solution

53. Find first repeated character.

Write a Python program to find the first repeated character in a given string.
Click me to see the sample solution

54. Find repeated character with smallest index.

Write a Python program to find the first repeated character in a given string where the index of the first occurrence is smallest.
Click me to see the sample solution

55. Find first repeated word in string.

Write a Python program to find the first repeated word in a given string.
Click me to see the sample solution

56. Find second most repeated word.

Write a Python program to find the second most repeated word in a given string.
Click me to see the sample solution

57. Remove spaces from string.

Write a Python program to remove spaces from a given string.
Click me to see the sample solution

58. Move spaces to front of string.

Write a Python program to move spaces to the front of a given string.
Click me to see the sample solution

59. Find maximum occurring character.

Write a Python program to find the maximum number of characters in a given string.
Click me to see the sample solution

60. Capitalize first and last letters of words.

Write a Python program to capitalize the first and last letters of each word in a given string.
Click me to see the sample solution

61. Remove duplicate characters in string.

Write a Python program to remove duplicate characters from a given string.
Click me to see the sample solution

62. Sum digits in string.

Write a Python program to compute the sum of the digits in a given string.
Click me to see the sample solution

63. Remove leading zeros in IP address.

Write a Python program to remove leading zeros from an IP address.
Click me to see the sample solution

64. Find max length of consecutive zeros (binary).

Write a Python program to find the maximum length of consecutive 0's in a given binary string.
Click me to see the sample solution

65. Common characters between two strings.

Write a Python program to find all the common characters in lexicographical order from two given lower case strings. If there are no similar letters print "No common characters".
Click me to see the sample solution

66. Make strings anagrams (retain characters).

Write a Python program to make two given strings (lower case, may or may not be of the same length) anagrams without removing any characters from any of the strings.
Click me to see the sample solution

67. Remove consecutive duplicates in string.

Write a Python program to remove all consecutive duplicates of a given string.
Click me to see the sample solution

68. Separate single and multiple occurrence chars.

Write a Python program to generate two strings from a given string. For the first string, use the characters that occur only once, and for the second, use the characters that occur multiple times in the said string.
Click me to see the sample solution

69. Find longest common substring.

Write a Python program to find the longest common sub-string from two given strings.
Click me to see the sample solution

70. Concatenate uncommon characters in strings.

Write a Python program that concatenates uncommon characters from two strings.
Click me to see the sample solution

71. Move spaces to front in single traversal.

>

Write a Python program to move all spaces to the front of a given string in a single traversal.
Click me to see the sample solution

72. Remove all except specified character.

Write a Python program to remove all characters except a specified character from a given string.
Original string
Python Exercises
Remove all characters except P in the said string:
P
Original string
google
Remove all characters except g in the said string:
gg
Original string
exercises
Remove all characters except e in the said string:
eee
Click me to see the sample solution

73. Count uppercase, lowercase, special, numeric.

Write a Python program to count Uppercase, Lowercase, special characters and numeric values in a given string.
Click me to see the sample solution

74. Minimum window with all chars of another string.

Write a Python program to find the minimum window in a given string that will contain all the characters of another given string.
Example 1
Input : str1 = " PRWSOERIUSFK "
str2 = " OSU "
Output: Minimum window is "OERIUS"
Click me to see the sample solution

75. Smallest window with all characters.

Write a Python program to find the smallest window that contains all characters in a given string.
Click me to see the sample solution

76. Substrings with k distinct characters.

Write a Python program to count the number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters.
Click me to see the sample solution

77. Count non-empty substrings.

Write a Python program to count the number of non-empty substrings of a given string.
Click me to see the sample solution

78. Count chars matching English alphabet position.

Write a Python program to count characters at the same position in a given string (lower and uppercase characters) as in the English alphabet.
Click me to see the sample solution

79. Find smallest and largest words.

Write a Python program to find the smallest and largest words in a given string.
Click me to see the sample solution

80. Substrings with same first and last char.

Write a Python program to count the number of substrings with the same first and last characters in a given string.
Click me to see the sample solution

81. Index of substring or "Not found".

Write a Python program to determine the index of a given string at which a certain substring starts. If the substring is not found in the given string return 'Not found'.
Click me to see the sample solution

82. Wrap string into paragraph with width.

Write a Python program to wrap a given string into a paragraph with a given width.
Sample Output:
Input a string: The quick brown fox.
Input the width of the paragraph: 10
Result:
The quick
brown fox.
Click me to see the sample solution

83. Print number in decimal, octal, hex, binary.

Write a Python program to print four integer values - decimal, octal, hexadecimal (capitalized), binary - in a single line.
Sample Output:
Input an integer: 25
Decimal Octal Hexadecimal (capitalized), Binary
25 31 19 11001
Click me to see the sample solution

84. Swap cases in string.

Write a Python program to swap cases in a given string.
Sample Output:
pYTHON eXERCISES
jAVA
nUMpY
Click me to see the sample solution

85. Bytearray to hexadecimal string.

Write a Python program to convert a given Bytearray to a Hexadecimal string.
Sample Output:
Original Bytearray :
[111, 12, 45, 67, 109]
Hexadecimal string:
6f0c2d436d
Click me to see the sample solution

86. Delete all occurrences of character.

Write a Python program to delete all occurrences of a specified character in a given string.
Sample Output:
Original string:
Delete all occurrences of a specified character in a given string
Modified string:
Delete ll occurrences of specified chrcter in given string
Click me to see the sample solution

87. Find common values in two strings.

Write a Python program to find the common values that appear in two given strings.
Sample Output:
Original strings:
Python3
Python2.7
Intersection of two said String:
Python
Click me to see the sample solution

88. Check string for capital, lower, number, length.

Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length.
Sample Output:
Input the string: W3resource
['Valid string.']
Click me to see the sample solution

89. Remove unwanted characters in string.

Write a Python program to remove unwanted characters from a given string.
Sample Output:
Original String : Pyth*^on Exercis^es
After removing unwanted characters:
Python Exercises
Original String : A%^!B#*CD
After removing unwanted characters:
ABCD
Click me to see the sample solution

90. Remove duplicate words in string.

Write a Python program to remove duplicate words from a given string.
Sample Output:
Original String:
Python Exercises Practice Solution Exercises
After removing duplicate words from the said string:
Python Exercises Practice Solution
Click me to see the sample solution

91. Convert heterogeneous list to string.

Write a Python program to convert a given heterogeneous list of scalars into a string.
Sample Output:
Original list:
['Red', 100, -50, 'green', 'w,3,r', 12.12, False]
Convert the heterogeneous list of scalars into a string:
Red,100,-50,green,w,3,r,12.12,False
Click me to see the sample solution

92. Find similarity between two strings.

Write a Python program to find string similarity between two given strings.
Sample Output:
Original string:
Python Exercises
Python Exercises
Similarity between two said strings:
1.0
Original string:
Python Exercises
Python Exercise
Similarity between two said strings:
0.967741935483871
Original string:
Python Exercises
Python Ex.
Similarity between two said strings:
0.6923076923076923
Original string:
Python Exercises
Python
Similarity between two said strings:
0.5454545454545454
Original string:
Java Exercises
Python
Similarity between two said strings:
0.0
Click me to see the sample solution

93. Extract numbers from string.

Write a Python program to extract numbers from a given string.
Sample Output:
Original string: red 12 black 45 green
Extract numbers from the said string: [12, 45]
Click me to see the sample solution

94. Hex color code to RGB tuple.

Write a Python program to convert a hexadecimal color code to a tuple of integers corresponding to its RGB components.
Sample Output:
(255, 165, 1)
(255, 255, 255)
(0, 0, 0)
(255, 0, 0)
(0, 0, 128)
(192, 192, 192)
Click me to see the sample solution

95. RGB to hex color code.

Write a Python program to convert the values of RGB components to a hexadecimal color code.
Sample Output:
FFA501
FFFFFF
000000
000080
C0C0C0
Click me to see the sample solution

96. Convert string to CamelCase.

Write a Python program to convert a given string to Camelcase.
Sample Output:
javascript
fooBar
fooBar
foo.Bar
fooBar
foobar
fooBar
Click me to see the sample solution

97. Convert string to snake_case.

Write a Python program to convert a given string to Snake case.
Sample Output:
java_script
foo_bar
foo_bar
foo.bar
foo_bar
foo_bar
foo_bar
Click me to see the sample solution

98. Decapitalize first letter in string.

Write a Python program to decapitalize the first letter of a given string.
Sample Output:
java Script
python
Click me to see the sample solution

99. Split multiline string to lines.

Write a Python program to split a multi-line string into a list of lines.
Sample Output:
Original string: This
is a
multiline
string.
Split the said multiline string into a list of lines:
['This', 'is a', 'multiline', 'string.', '']
Click me to see the sample solution

100. Check words for duplicate characters.

Write a Python program to check whether any word in a given string contains duplicate characters or not. Return True or False.
Sample Output:
Original text:
Filter out the factorials of the said list.
Check whether any word in the said sting contains duplicate characrters or not!
False
Original text:
Python Exercise.
Check whether any word in the said sting contains duplicate characrters or not!
False
Original text:
The wait is over.
Check whether any word in the said sting contains duplicate characrters or not!
True
Click me to see the sample solution

101. Add two strings as numbers.

Write a Python program to add two strings as if they were numbers (positive integer values). Return a message if the numbers are strings.
Sample Output:
42
Error in input!
Error in input!
Click me to see the sample solution

102. Remove punctuation from string.

Write a Python program to remove punctuation from a given string.
Sample Output:
Original text:
String! With. Punctuation?
After removing Punctuations from the said string:
String With Punctuation
Click me to see the sample solution

103. Replace long words with hash.

Write a Python program to replace each character of a word of length five and more with a hash character (#).
Sample Output:
Original string: Count the lowercase letters in the said list of words:
Replace words (length five or more) with hash characters in the said string:
##### the ######### ####### in the said list of ######
Original string: Python - Remove punctuations from a string:
Replace words (length five or more) with hash characters in the said string:
###### - ###### ############ from a #######
Click me to see the sample solution

104. Capitalize first letter of words.

Write a Python program that capitalizes the first letter and lowercases the remaining letters in a given string.
Sample Data:
("Red Green WHITE") -> "Red Green White"
("w3resource") -> "W3resource"
("dow jones industrial average") -> "Dow Jones Industrial Average"
Click me to see the sample solution

105. Extract name from email address.

Write a Python program to extract and display the name from a given Email address.
Sample Data:
("john@example.com") -> ("john")
("john.smith@example.com") -> ("johnsmith")
("fully-qualified-domain@example.com") -> ("fullyqualifieddomain")
Click me to see the sample solution

106. Remove repeated consecutive chars.

Write a Python program to remove repeated consecutive characters and replace them with single letters and print a updated string.
Sample Data:
("Red Green White") -> "Red Gren White"
("aabbbcdeffff") -> "abcdef"
("Yellowwooddoor") -> "Yelowodor"
Click me to see the sample solution

107. Count matches of three letters at same index.

Write a Python program that takes two strings. Count the number of times each string contains the same three letters at the same index.
Sample Data:
("Red RedGreen") -> 1
("Red White Red White) -> 7
("Red White White Red") -> 0
Click me to see the sample solution

108. Add hashes around non-vowels.

Write a Python program that takes a string and returns # on both sides of each element, which are not vowels.
Sample Data:
("Green" -> "-G--r-ee-n-"
("White") -> "-W--h-i-t-e"
("aeiou") -> "aeiou"
Click me to see the sample solution

109. Count leap years in a year range.

Write a Python program that counts the number of leap years within the range of years. Ranges of years should be accepted as strings.
Sample Data:
("1981-1991") -> 2
("2000-2020") -> 6
Click me to see the sample solution

110. Insert space before capital letters.

Write a Python program to insert space before every capital letter appears in a given word.
Sample Data:
("PythonExercises") -> "Python Exercises"
("Python") -> "Python"
("PythonExercisesPracticeSolution") -> "Python Exercises Practice Solution"
Click me to see the sample solution

111. Replace chars with position numbers.

Write a Python program that takes a string and replaces all the characters with their respective numbers.
Sample Data:
("Python") -> "16 25 20 8 15 14"
("Java") -> "10 1 22 1"
("Python Tutorial") -> "16 25 20 8 15 14 20 21 20 15 18 9 1 12"
Click me to see the sample solution

112. Add numbers given as strings.

Write a Python program to calculate the sum of two numbers given as strings. Return the result in the same string representation.
Sample Data:
( "234242342341", "2432342342") -> "236674684683"
( "", "2432342342") -> False ( "1000", "0") -> "1000"
( "1000", "10") -> "1010"
Click me to see the sample solution

113. Sort words alphabetically by first character.

Write a Python program that returns a string sorted alphabetically by the first character of a given string of words.
Sample Data:
("Red Green Black White Pink") -> "Black Green Pink Red White"
("Calculate the sum of two said numbers given as strings.") -> ("Calculate as given numbers of sum said strings. the two")
("The quick brown fox jumps over the lazy dog.") -> ("The brown dog. fox jumps lazy over quick the")
Click me to see the sample solution

Python Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.