Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Python Data Type: String - Exercises, Practice, Solution

Python String [101 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.]

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

2. Write a Python program to count the number of characters (character frequency) in a string. Go to the editor
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. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Go to the editor
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. 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. Go to the editor
Sample String : 'restart'
Expected Result : 'resta$t'
Click me to see the sample solution

5. 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. Go to the editor
Sample String : 'abc', 'xyz'
Expected Result : 'xyc abz'
Click me to see the sample solution

6. 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' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Go to the editor
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly'
Click me to see the sample solution

7. Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string. Go to the editor
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. Write a Python function that takes a list of words and return the longest word and the length of the longest one. Go to the editor
Sample Output:
Longest word: Exercises
Length of the longest word: 9
Click me to see the sample solution

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

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

11. Write a Python program to remove the characters which have odd index values of a given string. Go to the editor
Click me to see the sample solution

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

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

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

15. Write a Python function to create the HTML string with tags around the word(s). Go to the editor
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. Write a Python function to insert a string in the middle of a string. Go to the editor
Sample function and result :
insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]]
insert_sting_middle('{{}}', 'PHP') -> {{PHP}}
Click me to see the sample solution

17. 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). Go to the editor
Sample function and result :
insert_end('Python') -> onononon
insert_end('Exercises') -> eseseses
Click me to see the sample solution

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

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

20. Write a Python function to reverses a string if it's length is a multiple of 4. Go to the editor
Click me to see the sample solution

21. 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. Go to the editor
Click me to see the sample solution

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

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

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

25. Write a Python program to create a Caesar encryption. Go to the editor

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. Write a Python program to display formatted text (width=50) as output. Go to the editor
Click me to see the sample solution

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

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

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

30. Write a Python program to print the following floating numbers upto 2 decimal places. Go to the editor
Click me to see the sample solution

31. Write a Python program to print the following floating numbers upto 2 decimal places with a sign. Go to the editor
Click me to see the sample solution

32. Write a Python program to print the following floating numbers with no decimal places. Go to the editor
Click me to see the sample solution

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

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

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

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

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

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

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

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

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

42. Write a Python program to count repeated characters in a string. Go to the editor
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. Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder. Go to the editor
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. Write a Python program to print the index of the character in a string. Go to the editor
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. Write a Python program to check whether a string contains all letters of the alphabet. Go to the editor
Click me to see the sample solution

46. Write a Python program to convert a given string into a list of words. Go to the editor
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. Write a Python program to lowercase first n characters in a string. Go to the editor
Click me to see the sample solution

48. Write a Python program to swap comma and dot in a string. Go to the editor
Sample string: "32.054,23"
Expected Output: "32,054.23"
Click me to see the sample solution

49. Write a Python program to count and display the vowels of a given text. Go to the editor
Click me to see the sample solution

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

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

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

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

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

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

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

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

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

59. Write a Python program to find the maximum occurring character in a given string. Go to the editor
Click me to see the sample solution

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

61. Write a Python program to remove duplicate characters of a given string. Go to the editor
Click me to see the sample solution

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

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

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

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

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

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

68. Write a Python program to create two strings from a given string. Create the first string using those character which occurs only once and create the second string which consists of multi-time occurring characters in the said string. Go to the editor
Click me to see the sample solution

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

70. Write a Python program to create a string from two given strings concatenating uncommon characters of the said strings. Go to the editor
Click me to see the sample solution

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

72. Write a Python code to remove all characters except a specified character in a given string. Go to the editor
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. Write a Python program to count Uppercase, Lowercase, special character and numeric values in a given string. Go to the editor
Click me to see the sample solution

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

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

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

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

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

79. Write a Python program to find smallest and largest word in a given string. Go to the editor
Click me to see the sample solution

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

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

82. Write a Python program to wrap a given string into a paragraph of given width. Go to the editor
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. Write a Python program to print four values decimal, octal, hexadecimal (capitalized), binary in a single line of a given integer. Go to the editor
Sample Output:
Input an integer: 25
Decimal Octal Hexadecimal (capitalized), Binary
25 31 19 11001
Click me to see the sample solution

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

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

86. Write a Python program to delete all occurrences of a specified character in a given string. Go to the editor
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. Write a Python program find the common values that appear in two given strings. Go to the editor
Sample Output:
Original strings:
Python3
Python2.7
Intersection of two said String:
Python
Click me to see the sample solution

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

89. Write a Python program to remove unwanted characters from a given string. Go to the editor
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. Write a Python program to remove duplicate words from a given string. Go to the editor
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. Write a Python program to convert a given heterogeneous list of scalars into a string. Go to the editor
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. Write a Python program to find the string similarity between two given strings. Go to the editor
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. Write a Python program to extract numbers from a given string. Go to the editor
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. Write a Python program to convert a hexadecimal color code to a tuple of integers corresponding to its RGB components. Go to the editor
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. Write a Python program to convert the values of RGB components to a hexadecimal color code. Go to the editor
Sample Output:
FFA501
FFFFFF
000000
000080
C0C0C0
Click me to see the sample solution

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

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

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

99. Write a Python program to split a given multiline string into a list of lines. Go to the editor
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. Write a Python program to check whether any word in a given sting contains duplicate characrters or not. Return True or False. Go to the editor
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. Write a Python program to add two strings as they are numbers (Positive integer values). Return a message if the numbers are string. Go to the editor
Sample Output:
42
Error in input!
Error in input!
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



Python: Tips of the Day

Find current directory and file's directory:

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")
  • os.path.dirname(path) (returns "the directory name of pathname path")
  • os.getcwd() (returns "a string representing the current working directory")
  • os.chdir(path) ("change the current working directory to path")

Ref: https://bit.ly/3fy0R6m