As you know, the stings are widely used to hold textual data. To perform any programming tasks in Python, a good understanding of string manipulation is necessary.
These string exercises will help Python developers to learn and practice string operations, manipulations, slicing, and string functions.
Also Read:
This String Exercise includes the following: –
- It contains 18 Python string programs, questions, problems, and challenges to practice.
- The solution is provided for all questions.
- All string programs are tested on Python 3
Use Online Code Editor to solve exercise questions. Let us know if you have any alternative solutions in the comment section below.
Table of contents
- Exercise 1A: Create a string made of the first, middle and last character
- Exercise 1B: Create a string made of the middle three characters
- Exercise 2: Append new string in the middle of a given string
- Exercise 3: Create a new string made of the first, middle, and last characters of each input string
- Exercise 4: Arrange string characters such that lowercase letters should come first
- Exercise 5: Count all letters, digits, and special symbols from a given string
- Exercise 6: Create a mixed String using the following rules
- Exercise 7: String characters balance Test
- Exercise 8: Find all occurrences of a substring in a given string by ignoring the case
- Exercise 9: Calculate the sum and average of the digits present in a string
- Exercise 10: Write a program to count occurrences of all characters within a string
- Exercise 11: Reverse a given string
- Exercise 12: Find the last position of a given substring
- Exercise 13: Split a string on hyphens
- Exercise 14: Remove empty strings from a list of strings
- Exercise 15: Remove special symbols / punctuation from a string
- Exercise 16: Removal all characters from a string except integers
- Exercise 17: Find words with both alphabets and numbers
- Exercise 18: Replace each special symbol with # in the following string
Exercise 1A: Create a string made of the first, middle and last character
Write a program to create a new string made of an input string’s first, middle, and last character.
Given:
str1 = "James"
Code language: Python (python)
Expected Output:
Jms
Show Hint
- String index always starts with 0
- Use string indexing to get the character present at the given index
- Get the index of the middle character by dividing string length by 2
Show Solution
- Use string indexing to get the character present at the given index.
- Use
str1[0]
to get the first character of a string and add it to theresult
variable - Next, get the middle character’s index by dividing string length by 2.
x = len(str1) /2
. Usestr1[x]
to get the middle character and add it to theresult
variable - Use
str1[len(str1)-1]
to get the last character of a string and add it to theresult
variable - print
result
variable to display new string
Exercise 1B: Create a string made of the middle three characters
Write a program to create a new string made of the middle three characters of an input string.
Given:
Case 1
str1 = "JhonDipPeta"
Code language: Python (python)
Output
Dip
Case 2
str2 = "JaSonAy"
Code language: Python (python)
Output
Son
Show Hint
- First, get the middle index number by dividing string length by 2.
- Use string slicing to get the middle three characters starting from the middle index to the next two character
.
Show Solution
- Get the middle character’s index using
x = len(str1) /2
. - Use string slicing to get the middle three characters starting from the middle index to the next two character
str1[middle_index-1:middle_index+2]
Exercise 2: Append new string in the middle of a given string
Given two strings, s1
and s2
. Write a program to create a new string s3
by appending s2
in the middle of s1
.
Given:
s1 = "Ault"
s2 = "Kelly"
Code language: Python (python)
Expected Output:
AuKellylt
Show Hint
- Use built-in function
len(s1)
to get the string length. - Next, get the middle index number by dividing string length by 2.
Show Solution
- First, get the middle index number of
s1
by dividing s1’s length by 2 - Use string slicing to get the character from
s1
starting from 0 to the middle index number and store it inx
- concatenate
x
ands2
.x = x + s2
- concatenate
x
and remeaning character froms1
- print
x
Exercise 3: Create a new string made of the first, middle, and last characters of each input string
Given two strings, s1
and s2
, write a program to return a new string made of s1 and s2’s first, middle, and last characters.
Given:
s1 = "America"
s2 = "Japan"
Code language: Python (python)
Expected Output:
AJrpan
Show Hint
- String index starts with index 0. The first character is present at index 0, and the last character is at the index string’s length -1
- Use built-in function
len(s1)
to get the string length. - Next, get the middle index number by dividing string length by 2.
Show Solution
- Get the first character from both strings, concatenate them, and store them in variable
x
- Get the middle character from both strings, concatenate them, and store them in variable
y
- Get the last character from both strings, concatenate them, and store them in variable x
- In the end, join
x
,y
, andz
and save it in the resultvariable
- print the
result
Exercise 4: Arrange string characters such that lowercase letters should come first
Given string contains a combination of the lower and upper case letters. Write a program to arrange the characters of a string so that all lowercase letters should come first.
Given:
str1 = PyNaTive
Expected Output:
yaivePNT
Show Hint
Iterate each character from a string and check if the current character is the lower or upper case using islower()
string function
Show Solution
- Create two lists lower and upper
- Iterate a string using a for loop
- In each loop iteration, check if the current character is the lower or upper case using the
islower()
string function. - If a character is the lower case, add it to the lower list, else add it to the upper list
- to join the lower and upper list using a
join()
function. - convert list to string
- print the final string
Exercise 5: Count all letters, digits, and special symbols from a given string
Given:
str1 = "P@#yn26at^&i5ve"
Code language: Python (python)
Expected Outcome:
Total counts of chars, digits, and symbols Chars = 8 Digits = 3 Symbol = 4
Show hint
Use the following string functions
isalpha()
: To check if a string/character is an alphabetisdigit()
: To check if a string/character is a digit.
Show Solution
- Iterate each character from a string using a
for
loop - In each loop iteration, check if the current character is the alphabet using an
isalpha()
function. If yes, increase the character counter. Check if it is a digit using theisdigit()
function and increase the digit counter; otherwise, increase the symbol counter. - Print the value of each counter
Exercise 6: Create a mixed String using the following rules
Given two strings, s1 and s2. Write a program to create a new string s3 made of the first char of s1, then the last char of s2, Next, the second char of s1 and second last char of s2, and so on. Any leftover chars go at the end of the result.
Given:
s1 = "Abc"
s2 = "Xyz"
Code language: Python (python)
Expected Output:
AzbycX
Show Solution
Exercise 7: String characters balance Test
Write a program to check if two strings are balanced. For example, strings s1 and s2 are balanced if all the characters in the s1 are present in s2. The character’s position doesn’t matter.
Given:
Case 1:
s1 = "Yn"
s2 = "PYnative"
Code language: Python (python)
Expected Output:
True
Case 2:
s1 = "Ynf"
s2 = "PYnative"
Code language: Python (python)
Expected Output:
False
Show Hint
Iterate each character from a string s1 and check if the current character is present in the string s2.
Show Solution
Exercise 8: Find all occurrences of a substring in a given string by ignoring the case
Write a program to find all occurrences of “USA” in a given string ignoring the case.
Given:
str1 = "Welcome to USA. usa awesome, isn't it?"
Code language: Python (python)
Expected Outcome:
The USA count is: 2
Show Hint
Use the string function count()
Show Solution
Exercise 9: Calculate the sum and average of the digits present in a string
Given a string s1, write a program to return the sum and average of the digits that appear in the string, ignoring all other characters.
Given:
str1 = "PYnative29@#8496"
Code language: Python (python)
Expected Outcome:
Sum is: 38 Average is 6.333333333333333
Show Hint
Iterate each character from a string s1 and check if the current character is digit using the isdigit()
function
Show Solution
Solution 1: Use string functions
- Iterate each character from a string
s1
using a loop - In the body of a loop, check if the current character is digit using the
isdigit()
function - If it is a digit, then add it to the sum variable
- In the end, calculate the average by dividing the total by the count of digits
Solution 2: Use regular expression
Exercise 10: Write a program to count occurrences of all characters within a string
Given:
str1 = "Apple"
Code language: Python (python)
Expected Outcome:
{'A': 1, 'p': 2, 'l': 1, 'e': 1}
Show Hint
Use the string function count()
Show Solution
- create an empty dictionary to store the result. character is the key, and the count is the value
- Iterate each character from a string
s1
using a loop - In the body of a loop, use the
count()
function to find how many times a current character appeared in a string - Add key-value pair in a dictionary
Exercise 11: Reverse a given string
Given:
str1 = "PYnative"
Code language: Python (python)
Expected Output:
evitanYP
Show Hint
- Use negative slicing
- Or use the built-in function
reversed()
.
Show Solution
Solution 1: Negative String slicing
Solution 2: Using the reversed()
function
Exercise 12: Find the last position of a given substring
Write a program to find the last position of a substring “Emma” in a given string.
Given:
str1 = "Emma is a data scientist who knows Python. Emma works at google."
Code language: Python (python)
Expected Output:
Last occurrence of Emma starts at index 43
Show Hint
Use the string function rfind()
Show Solution
Exercise 13: Split a string on hyphens
Write a program to split a given string on hyphens and display each substring.
Given:
str1 = Emma-is-a-data-scientist
Code language: Python (python)
Expected Output:
Displaying each substring Emma is a data scientist
Show Hint
Use the string function split()
Show Solution
Exercise 14: Remove empty strings from a list of strings
Given:
str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
Code language: Python (python)
Expected Output:
Original list of sting ['Emma', 'Jon', '', 'Kelly', None, 'Eric', ''] After removing empty strings ['Emma', 'Jon', 'Kelly', 'Eric']
Show Hint
- Use the built-in function
filter()
to remove empty strings from a list - Or use the for loop and
if
condition to remove the empty strings from a list
Show Solution
Solution 1: Using the loop and if
condition
Solution 2: Using the built-in function filter()
Exercise 15: Remove special symbols / punctuation from a string
Given:
str1 = "/*Jon is @developer & musician"
Code language: Python (python)
Expected Output:
"Jon is developer musician"
Show Hint
Use string functions translate()
and maketrans()
- Use the
translate()
function to get a new string where specified characters are replaced with the character described in a dictionary or a mapping table. - Use the
maketrans()
function to create a mapping table.
Or Use the regex in Python. See Python regex replace.
Show Solution
Solution 1: Use string functions translate()
and maketrans()
.
The string.punctuation
constant contain all special symbols.
Solution 2: Using regex replace pattern in a string
Exercise 16: Removal all characters from a string except integers
Given:
str1 = 'I am 25 years and 10 months old'
Code language: Python (python)
Expected Output:
2510
Show Hint
Use the string function isdigit()
Show Solution
Exercise 17: Find words with both alphabets and numbers
Write a program to find words with both alphabets and numbers from an input string.
Given:
str1 = "Emma25 is Data scientist50 and AI Expert"
Code language: Python (python)
Expected Output:
Emma25
scientist50
Show Hint
Use the built-in function any()
with the combination of string functions isalpha()
and isdigit()
Show Solution
Exercise 18: Replace each special symbol with # in the following string
Given:
str1 = '/*Jon is @developer & musician!!'
Code language: Python (python)
Expected Output:
##Jon is #developer # musician##
Show Hint
Use string function replace()
Show Solution
- Use the
string.punctuation
constant to get the list of all punctuations - Iterate each symbol from a punctuations
- Use string function
replace()
to replace the current special symbol in a string with #