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.
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 theresultvariable - 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 theresultvariable - Use
str1[len(str1)-1]to get the last character of a string and add it to theresultvariable - print
resultvariable 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
s1by dividing s1’s length by 2 - Use string slicing to get the character from
s1starting from 0 to the middle index number and store it inx - concatenate
xands2.x = x + s2 - concatenate
xand 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, andzand 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
forloop - 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
s1using 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
s1using 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-scientistCode 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
ifcondition 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.punctuationconstant 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 #

# Exercise 16: Removal all characters from a string except integers
import string
str1 = ‘I am 25 years and 10 months old’
word=””.join([x for x in str1 if x.isdigit()])
print(word)
Exercise 17: Find words with both alphabets and numbers
def alpdit(text):
word=[x for x in text.split() if not x.isalpha()]
return word
print(alpdit(“Emma25 is Data scientist50 and AI Expert”))
# Exercise 10: Write a program to count occurrences of all characters within a string
str1=”abcdabcdabcd”
print(dict((char, str1.count(char)) for char in str1))
Exercise 9: Calculate the sum and average of the digits present in a string
str1=”123daf45sdfdsf”
nums=[int(num) for num in str1 if num.isdigit()]
print(sum(nums), sum(num)/len(nums))
Exercise 8: Find all occurrences of a substring in a given string by ignoring the case
import re
str1=”Welcome to Python To Python too”
str2=”to”
pattern = re.compile(‘\\b’+str2+’\\b’, re.IGNORECASE)
print(len(pattern.findall(str1)))
Exercise 7: String characters balance Test
str1 = “Yellow”
str2 = “Yell”
balanced = False
if all(i in str1 for i in str2) or all(i in str2 for i in str1):
balanced = True
print(f”{str1} and {str2} are balanced: {balanced}”)
I think u are right
#task 7
a=input(“enter a word: “)
b=input(“enter b word: “)
rule=””
if(len(a)==len(b)):
for i in range(len(a)):
rule+=a[i]
rule+=b[len(b)-1-i]
print(rule)
else:
print(“MUst be the same length !”)
# task 19
txt=input(“enter a text: “)
newTxt=””
for l in txt:
if l==” “:
newTxt+=” ”
elif not l.isalnum():
l=”#”
newTxt+=l
print(“result:”,newTxt )
s1 = “sdf”
s2 = “gth”
# AzbycX
first=s1[0]+s2[-1]
middle=s1[int(len(s1)/2)]+s2[int(len(s2)/2)]
last=s1[-1]+s2[0]
print(first+middle+last)
Exercise 1.A
str1=”James”
print(f'{str1[0]}{str1[len(str1)//2]}{str1[-1]}’)
Last exercise
str1 = “/*Jon is @developer & musician!!”
str=” ”
for i in range(0,len(str1)):
if str1[i].isalnum() or str1[i].isspace():
str+=str1[i]
else:
str+=”#”
print(str)
Exercise 1A:
This will give “J M S” for 5 character long string and “N A” for 7 character long string
# str1 = “James”
str1 = “Banana”
length_ = round(len(str1)) // 2
print(str1[0]) # first
if len(str1) % 2:
print((str1[length_])) # middle
else:
print((str1[length_ – 1]), (str1[length_])) # middle
print(str1[len(str1) – 1]) # last
Here is the best answer
1A. Write a program to create a new string made of an input string’s first, middle, and last character.
str1 = “James”
str1[0::2]
3. 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
s1 = “America”
s2 = “Japan”
s1[0]+s2[0]+s1[len(s1)//2]+s2[len(s2)//2]+s1[-1]+s2[-1]
This one works only for a string with 5 characters like James, this answer is universal: str1 = “abcdefghj”
print(str1[0::int(len(str1)/2)]) , if you assigned to str1 a string with an even number of characters it will output the first middle and last character of string.
# 17
def stay_alnum(string):
for item in string.split():
if not(item.isalpha()) and not(item.isdigit()):
print(item)
#17
i think i had a similar solution:
str1 = “Emma25 is Data scientist50 and AI Expert”
for i in str1.split():
if i.isalpha() or i.isdigit():
continue
else:
print(i)
Exercise 7:
def balance(s1, s2):
ct = s2.count(s1)
if ct > 0:
return True
else:
return False
x = “Ynf”
y = “PYnative”
z = balance(x, y)
print(z)
exercise 10
str1 = “Apple”
dict_str1 = {}
for i in str1:
dict_str1[i] = 0
for k in dict_str1:
count = str1.count(k)
dict_str1[k] += count
print(dict_str1)
exercise 8
str1 = “Welcome to USA. usa awesome, isn’t it?”
spl = str1.split()
for pos in range(len(spl)):
pos1 = spl[pos]
if spl[pos] == “USA.”:
print(f”USA pos is: {pos}”)
exercise 6
s1 = “Abc”
s2 = “Xyz”
for i in range(len(s2)):
rev = s2[-1-i]
s1.split()
j = “”.join((s1[i] + rev))
print(j, end=”)
Exercise 1
str1 = “James”
for i in range(len(str1)):
if i % 2 == 0:
print(str1[i], end=””)
This will produce answer for the word “Python” as “Pto, and “Strings” as “Srns”
Q15
def rem_sym(str1):
for i in str1:
for j in i:
if j in “!@#$%^&*?/”:
str1=str1.replace(i,””)
print(str1)
str1 = “/*Jon is @developer & musician”
rem_sym(str1)
my solution to question 6:
def mixing(s1, s2):
s3 = ”
l1 = len(s1)
l2 = len(s2)
l = min(l1, l2)
print(l)
for i in range(l):
s3 = s3 + s1[i] + s2[l1-1-i]
print(s3)
if l1 > l2:
s3 += s1[l:]
elif l2 > l1:
s3 += s2[l:]
return s3
s1 = “Abc”
s2 = “Xyz”
s3 = mixing(s1, s2)
print(s3)
the 12th one can also be done by using
n=str1.index(“Emma”)
print(str1.index(“Emma”,n+1,len(str1)))
question2
str1 = “auly”
str2 = “kelly”
middle = int(len(str1)/2)
x=str1[:middle]+str2+str1[middle:]
print(x)
Question2
str1= “Auly”
middle = int(len(str1)/2)
str2= “kelly”
print(str1[:middle],str2,str1[middle:])
question4
str1 = “auly”
str2 = “kelly”
middle = int(len(str1)/2)
x=str1[:middle]+str2+str1[middle:]
print(x)
Ans for #17
str1 = “Emma25 is Data scientist50 and AI Expert”
for item in str1.split():
if not item.isdigit or not item.isalpha():
print(item,end=’\n’)
A1راه حل بسیار کوتاه و عالی برای سوال
str1 = “Jemes”
print(str1)
res = str1[:: 2]
print(“new string:”, res)
str=’james’
print(“Original string is: “,str)
res=str[0]+str[2]+str[-1]
print(“New string is: “,res)
Q.16 Using Regex.
import restr1 = 'I am 25 years and 10 months old'
res=re.findall('\d+',str1)
str_val="".join(res)
print(str_val)
OUTPUT:
2510
Q.17 Using Regex.
import restr1 = "Emma25 is Data scientist50 and AI Expert"
res=re.findall('\w+\d+',str1)
for val in res:
print(val)
OUTPUT:
Emma25
scientist50
my solution of q15
str1 = "/*Jon is @developer & musician"str = ''
for i in str1:
if i.isalnum() or i.isspace():
str += i
print(str)
Firstly… this site is incredible and thank you so much for the time and effort you’ve put into this so we can all enjoy .^_^.
Exercise 4:
def lower_order(a:str)->str:new = ""
for letter in a:
if letter.islower():
new += letter
for letter in a:
if letter.isupper():
new += letter
return(new)
s1 = "PyNaTive"
print(lower_order(s1))
Question 2
str1 = input("Enter 1st word: ")str2 = input("Enter 2nd word: ")
len1 = (len(str1))//2
print(str1[0:len1]+str2+str1[len1:])
str1 = input("Enter 1st word: ")len1 = (len(str1))//2
print(str1[len1-1:len2+2])
exercise 18:
str1 = '/*Jon is @developer & musician!!'old="/ * @ & ! !"
new="# # # # # #"
print(str1.translate(str.maketrans(old,new)))
Exercise 18:
simple answer compared to exiting answer..
I hope this answer is helpful..
str1 = '/*Jon is @developer & musician!!'old="/ * @ & ! !"
new="# # # # # #"
change=str.maketrans(old,new)
print(str1.translate(change))
if you have hundreds of punctuations it is hard to replace like this
# 1B
def exe(x):mid = int(len(x)/2)
print(x[mid-1:mid+2])
# 1A
print(x[::int(len(x)/2)])question 1:
a="james"a1=a[0]
a2=a[2]
a3=a[-1]
b=a1+a2+a3
print(b)
Question 7 :
s1 = "Yn"s2 = "PYnative"
print(all(item in s2 for item in s1))
str1 = "PyNaTive"lowercase = ""
uppercase = ""
for char in str1:
if char.islower():
lowercase = lowercase + char
else:
uppercase = uppercase + char
result = lowercase + uppercase
print(result)
Exercise 4:
Solution for 1A.
str='james'print(str[0:6:2])
question 17
I think you can omit the first condition just like this:
str1 = "Emma25 is Data scientist50 and AI Expert"str1_list = str1.split()
for i in str1_list:
for j in i:
if j.isdigit():
print(i)
break
(Pretty) Short Solution for Exercise 6:
AzbycX Traceback (most recent call last):s3 = s1[index] + s2[-index-1]
IndexError: string index out of range
here I got the index error can you please check the code once
Short Solution of Exercise 14
None will come
This is an alternate solution for Exercise 5
This is another more concise alt solution to exercise 5
Solution for exercise number 1, take into a count in case the length of the string when divided by 2 does not =0
Exercise 3:
Output:
Output:
for exercise 17:
hey, thanks your code helped me solve this question.
please have a look at how I modified ur code, and it optimized
Very good champ
ex 3 answer
Q 01:
add string s2 in middle of s1 string
for exercise 7:
please delete my previous reply
for number 14
i forgot to add
s1.remove(None)thoughAlternate solution of Exercise 15: Remove special symbols/punctuation from a string
Can you pleas explain to me this code
For Problem 16
Q 15
Example-18
Ex- 18
str1 = “/*Jon is @developer!@#,><"
for i in str:
if i not in specialSymbols:
newStrList += i
return newStrList
print(removeSpecialSymbol(str1))
Question 6 alternative solution:
Exercise 6
Exercise 10:
So, here’s the thing that I simply can’t understand. I tried the “if not i.isalpha” in order to filter the letters and also “if not i.isdigit” so it can be considered a complete filter for showing the symbols of a string. I printed i and I saw that it works. But then, the replacement worked only for the “!” and not the rest. So, I made a third-string outside of the for loop and I replaced “@” with “#” and it worked. So, why doesn’t the replace work completely inside the for loop, but when I use it outside of it with symbols that I had taken, it does?
QN 17
str1 = "emma25 is Data scientist50 and AI Expert" m=(str1.split()) q=[] for i in m: for j in i: if j.isdigit(): for x in i: if x.isalpha(): q.append(i) w=(set(q)) m=list(w) for i in range(len(w)): print(m[i])str1 = "Emma25 is Data scientist50 and AI Expert"str2=str1.split()
l=''
for i in str2:
if i.isalpha():
None
else:
l=l+'\n'+i
print(l)
#Output
##Emma25
##scientist50
Q13:
using list comprehension:
Exercise 3
Exercice 1A
Exercise 3
Q15
output:
Jon is developer musician
Q9
You’re an amazing thinker bro! I was very close to doing it on my own… But this piece has really broadened my horizon! God bless you
Exercise 16:
Q.9:
Q.8:
can you give the code without using count function or any other inbuilt pythons libraries
Question-5:
Output:
Exercise:4
Exercise:3
Exercise 2:
Output: AuKellylt
Exercise 2:
Question 1:
Anyone explain Q2 , I can’t understand that …? Pls help me
Exercise 2:
Output: AuKellylt
Q6 Alternate Solution
Wow, where have you been all my life? Thank you ???? You have made the world a better place.
17.
I like the way you put it.
I would suggest the code ends like this to match the expected output.
Question 1
with string as user input and length and odd length checking
For Q 17
Thanks awesome way brilliant thinking!!
Alternative for Q. 13
Another solution for question 4:
For, Question 6,
For Question 15: (could be a simple solution)
another solution to question 18:
another solution to question 16
I Just Wanna Know, Is this method is Correct or Not
# Question 1
Another solution to question 7:
Exercise 7
Another solution to question 1
A solution to question 14
A solution to Question 5
The solution to Question 10
The solution to Question 9
The solution to Question 7
The solution to Question 6:
A solution to question 3
Question 3
Beautiful!
Question 3
Question 2
Hi, total newbie here. with Exercise Question 6: Given two strings, s1 and s2, create a mixed String, there is reference made to the length of s1 and s2 in the function. Why is the length of the string relevant to the loop and in turn mixing of the strings? Thanks in advance.
The answer of question no 12
This is really helpful. Thanks
q17:
where is ques
Alternative:
str1 = “Emma25 is Data scientist50 and AI Expert”
for i in str1.split():
if not i.isalpha():
print(i)
ques 9 better methods to use regex than the listed above
MY WAY OF SOLVING QUESTION NUMBER 1
question 5
Q6: The solution didn’t account for the remaining letters to be added at the end.
My solution works for strings of any length, and also adds remaining letters at the end.
Exercise Question 18
Exercise Question 9:
thanks a lot
Exercise Question 7: String characters balance Test
exercise-4
Q12: Alternative solution with for loop and count() function.
Q12: Alternative solution
incoming question 7.
By the way, bro this site is THE BEST for beginners like me.
for question number 9
can anyone please point out anything that I may have done wrong.
QUESTIONS 4 and 5
why use
split()?i found no purpose.
is it to remove space ?
As of now, I have removed as there is a single word in the string. If you have a string with multiple words we need to use
split().Q6: I made an alternative solution that doesn’t require reversing one of the strings, and uses a while loop instead of for loop.
So my solution was pasted incorrectly… Here is the correct version:
For some reason I can’t post it correctly…
this part is supposed to be between first and second if statement:
Hello
Solution for Q. 9
Above solution is for Q8
For question 7, as of 07-26-2020, the expected output should be “True” for Case 1. This is according to your code and description. s1 does exist within s2 for Case 1. This threw me when I was trying to solve the exercise, as I thought maybe you meant that s1 and s2 must be identical except for ordering. As you can imagine, the code for that would be different.
You are right, Mark. I have updated the expected output
Exercise Question 9
None of the answers to Q 4, including the solution given, produce the required answer
i.e. aeiNPTvy
Yes, it was mistakenly written I have removed the condition
Answer for first could be;
Q: 7 Alternative solution hope it helps to understand better.
Hi,
My solution for Q10:
Question 5
Hi,
My solution for Q9:
Hi,
My solution for Q5:
Hi,
My solution for Q4:
The answer of Q:2 is wrong.
The correct answer is:
def appendMiddle(s1, s2): middleIndex = int(len(s1) /2) print("Original Strings are", s1, s2) middleThree = s1[:middleIndex:]+ s2 +s1[middleIndex:] print("After appending new string in middle", middleThree) appendMiddle("Chrisdem", "IamNewString")Really Helpful thanks a lot
Q8 character count
str1 = "Welcome to USA. usa awesome, isn't it?" count_char = str1.lower().count("usa") print(count_char)output : 2
str1 = "Welcome to USA. usa awesome, isn't it?" count_char = str1.lower().count("usa") print(count_char)you should have used __contains__() function also
Q9:
sumAndAverage = ("English = 78 Science = 83 Math = 68 History = 65") sum = 0 count = 0 for i in sumAndAverage.split(): if i.isnumeric(): sum += int(i) count +=1 print("Total Marks are: ", sum) print("Percentage is: ", sum/count)Q8: simplest way.
Q7: The simplest solution.
flag = True if set(input("Enter the string: ")).issubset(input("Enter the string: ")): print("s1 and s2 are balanced: ", flag) else: flag = False print("s1 and s2 are balanced ", flag)Q6 : without function.
s1 = "Pynative" s2 = "Website" s2 = s2[::-1] ls1 = len(s1) ls2 = len(s2) len = ls1 if ls1 > ls2 else ls2 res = "" for i in range(len): if i < ls1: res = res + s1[i] if i < ls2: res = res + s2[i] print(res)Q5:
s1 = "P@#yn26at^&i5ve" low = 0 upp = 0 num = 0 spl = 0 for i in s1: if i.islower(): low += 1 elif i.isupper(): upp += 1 elif i.isnumeric(): num += 1 else: spl += 1 print("Lower Chars = ",low,"\nUpper Chars = ",upp,"\nNumbers = ",num,"\nSpecial chars = ",spl)Q4:
s1 = 'PyNaTive' low = [] upp = [] for i in s1: if i.islower(): low.append(i) else: upp.append(i) s2 = ''.join(low + upp) print("arranging characters giving precedence to lowercase letters: \n" + s2)Question 3:
Hi Nikhil, thanks for posting these solutions. I have a question regarding getting the middle character for both strings – do you know why you would need the string variable (s1, s2) in front of the equation to obtain the middle variable? It seems redundant to me as you already have the variable in the equation. Thanks!
Q2: The simplest solution.
Q1:
i like this answer as a beginner i am getting this quick and easy.
Dear Vishal, Its a time to appreciate you for your entire efforts to publish the site. This is really very helpful to understand from very beginning. I am based at Bangalore India and can help you out in case of any further business thoughts like Data Science implementations or more.
Of course yes, I have not seen such types of stuffs and the exercise with the detailed solutions. !!! Highly Appreciated .. 🙂
Hey, Prakash, Thank you very much, It means a lot to me. Thanks for taking the time to let me know. When I start covering Data Science, I will let you know.
you didn’t explain arguments in Q9 for the func of re.findall. I get that but I suggest to explain them all for the new visitors to understand easily.
Thank you, Abdullah, for letting us know. Yes, we are planning to add a description to each question. You will see the changes in the coming days
Yes Abdullah, This is a valid point. However Vishal has mentioned that on upcoming modules, he is planning to add.
I requested to Abdullah to please explain the same in this comments as well, so that any of the new visitor can understand after reading this comments.
x='' y='' p ='SoMnaTh' for i in range(len(p)): #upper case letter if p[i].upper()==p[i]: x =x+p[i] for i in range(len(p)): #lower case letter if p[i].lower()==p[i]: y=y+p[i] z = x+y #concatenateQuestion:1
Given a string of odd length greater 7,return a string made of the middle three chars of a given String
Answer:
a=input("Enter the String:") b=0 n=0 for i in a: b=b+1 if(b%2==1): n=b//2 print((a[n-1:n+2]))solution 9:
def sum_average(s: str): l = [] num = 0 i = 0 while i < len(s): if s[i].isdigit(): num = int(s[i]) j = i + 1 while j < len(s) and s[j].isdigit(): num = num * 10 + int(s[j]) j += 1 i += 1 l.append(num) i += 1 return [sum(l), sum(l)/len(l)] result = sum_average('English = 78 Science = 83 Math = 68 History = 65') print('sum', result[0], 'average', result[1])Solution for Q1:
word = input("word: ") if len(word)>=7 and len(word)%2 != 0: n = (len(word)-3)//2 newWord1 = word[n:] middleThree = newWord1[:3] print("original word is: ", word) print("middle three chars are: ",middleThree) else: print("word have less then 7 letters")string = input("Please enter your string: ") my_string = len(string)+1 if len(string) % 2 ==0: our_string = len(string) else: our_string = my_string upper = (int(our_string) / 2)-2 lower = ((int(our_string)/2)* (-1))+1 upper = int(upper) lower = int(lower) print(string[upper:lower])Solution for Q9:
def sumofnum(input): x=input.split() sum=0 count=0 for eachvalue in input: if eachvalue.isnumeric(): sum+=int(eachvalue) count+=1 else: print(eachvalue) average = (sum/count) print("Sum of integers:", sum) print("Count of Integers:", count) print("Average of integers:", average) sumofnum("56xyz1234")Bill’s solution to Question 4 is very elegant. Being a beginner, I really don’t understand it, but thanks for posting. I’ll keep studying.
Question 4 – I asked for user input. I think my solution is more straightforward than the one provided.
def printLowerfirst(s1): lowers = '' uppers = '' for char in my_word: if char.islower(): lowers += char else: uppers += char return lowers + uppers word = input("Enter a word: ") print("Your word:", word) print("Your word with lowercase letters first:", printLowerfirst(word))Q10
str1 = input("Input word : ") print({c : str1.count(c) for c in str1})Question 6: Please don’t give complicated solutions to easy problems, when we can solve these by easy methods
Your answer is right if both the string lengths are equal. Else it is coming as list index out of range.
bro please check your code, it has errors
🤔🤔
Q10 – I offer my slightly different solution:
import pprint def char_frequency(txt): char_counts = {} for i in range(len(txt)): char_counts.setdefault(txt[i], 0) char_counts[txt[i]] += 1 return char_counts pprint.pprint(char_frequency('abbcccddddeeeeeeeeeee')){'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 11}Q9 A very minor point, but in both the example and solution you use the word Percentage instead of Average. My solution without using regex (which mostly confuses me) is as follows:
def sum_and_average(string): lst = string.split() sum_int = 0 count_int = 0 for token in lst: if token.isdigit(): count_int += 1 sum_int += int(token) return (sum_int, sum_int/count_int) marks = 'English = 78 Science = 83 Math = 68 History = 65' result = sum_and_average(marks) print(f'Total marks earned = {result[0]}') print(f'Average mark = {result[1]}')Total marks earned = 294
Average mark = 73.5
Q7 I know it’s not what you were looking for, but my essentially one-liner is
def is_balanced(a, b): return set(a).issubset(set(b)) s1 = 'rose' s2 = 'My arm is sore' print(f'Are "{s1}" and "{s2}" balanced? {is_balanced(s1, s2)}') s2 = 'My arm is sort of limp' print(f'Are "{s1}" and "{s2}" balanced? {is_balanced(s1, s2)}')Are “rose” and “My arm is sore” balanced? True
Are “rose” and “My arm is sort of limp” balanced? False
Q6 again. I offer an alternative solution:
def mix_string(x, y): in_range = min(len(x), len(y)) end = -1 result = [] for i in range(in_range): result.append(x[i]) result.append(y[end]) end -= 1 if len(x) > len(y): result.append(x[abs(end) - 1:]) elif len(y) > len(x): result.append(y[:end + 1]) return ''.join(result)It took me longer to understand what was required for Q6 than to come up with the solution! May I suggest a rewording of the question along the following lines:
Given two strings, s1 and s2, create a “mix string” such that the new string is made up of the first character of s1 followed by the last char of s2, then the second character of s1 followed by the penultimate character of s2, and so on. Any left-over characters from the longer string go at the end of the result.
Hey, Bill will reword the question 6. Thank you for all your comments and suggestion. Yes, there can be multiple alternative solutions for each question. I kept it simple because it is beginners exercises.
The example shown for Q4 is incorrect: only some of the lowercase characters appear before the uppercase ones.
My alternative solution to the one given is:
yvieaTPN
I just figured out what you did here. You used the ASCII values. I’m a beginner and the only reason I figured it out was that I kept wondering what was sorted in reverse. To confirm, I ran the program having it print ord() of each character. I could also have simply looked them up.
Pretty neat solution.
It does not match the expected output.
Having interpreted the ambiguous wording of Q3 as meaning the first middle and last characters of s1 then the same for s2, my solution is:
Output:
playlet
heaps of iron
python