PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python String Exercise with Solutions

Python String Exercise with Solutions

Updated on: March 13, 2025 | 234 Comments

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:

  • Python String Quiz
  • Python String Interview Questions

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 the result variable
  • Next, get the middle character’s index by dividing string length by 2. x = len(str1) /2. Use str1[x] to get the middle character and add it to the result variable
  • Use str1[len(str1)-1] to get the last character of a string and add it to the result variable
  • print result variable to display new string
str1 = 'James'
print("Original String is", str1)

# Get first character
res = str1[0]

# Get string size
l = len(str1)
# Get middle index number
mi = int(l / 2)
# Get middle character and add it to result
res = res + str1[mi]

# Get last character and add it to result
res = res + str1[l - 1]

print("New String:", res)Code language: Python (python)

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]
def get_middle_three_chars(str1):
    print("Original String is", str1)

    # first get middle index number
    mi = int(len(str1) / 2)

    # use string slicing to get result characters
    res = str1[mi - 1:mi + 2]
    print("Middle three chars are:", res)

get_middle_three_chars("JhonDipPeta")
get_middle_three_chars("JaSonAy")Code language: Python (python)

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 in x
  • concatenate x and s2. x = x + s2
  • concatenate x and remeaning character from s1
  • print x
def append_middle(s1, s2):
    print("Original Strings are", s1, s2)

    # middle index number of s1
    mi = int(len(s1) / 2)

    # get character from 0 to the middle index number from s1
    x = s1[:mi:]
    # concatenate s2 to it
    x = x + s2
    # append remaining character from s1
    x = x + s1[mi:]
    print("After appending new string in middle:", x)

append_middle("Ault", "Kelly")
Code language: Python (python)

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, and z and save it in the result variable
  • print the result
def mix_string(s1, s2):
    # get first character from both string
    first_char = s1[0] + s2[0]

    # get middle character from both string
    middle_char = s1[int(len(s1) / 2):int(len(s1) / 2) + 1] + s2[int(len(s2) / 2):int(len(s2) / 2) + 1]

    # get last character from both string
    last_char = s1[len(s1) - 1] + s2[len(s2) - 1]

    # add all
    res = first_char + middle_char + last_char
    print("Mix String is ", res)

s1 = "America"
s2 = "Japan"
mix_string(s1, s2)
Code language: Python (python)

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
str1 = "PYnAtivE"
print('Original String:', str1)
lower = []
upper = []
for char in str1:
    if char.islower():
        # add lowercase characters to lower list
        lower.append(char)
    else:
        # add uppercase characters to lower list
        upper.append(char)

# Join both list
sorted_str = ''.join(lower + upper)
print('Result:', sorted_str)Code language: Python (python)

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 alphabet
  • isdigit(): 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 the isdigit() function and increase the digit counter; otherwise, increase the symbol counter.
  • Print the value of each counter
def find_digits_chars_symbols(sample_str):
    char_count = 0
    digit_count = 0
    symbol_count = 0
    for char in sample_str:
        if char.isalpha():
            char_count += 1
        elif char.isdigit():
            digit_count += 1
        # if it is not letter or digit then it is special symbol
        else:
            symbol_count += 1

    print("Chars =", char_count, "Digits =", digit_count, "Symbol =", symbol_count)

sample_str = "P@yn2at&#i5ve"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)
Code language: Python (python)

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
s1 = "Abc"
s2 = "Xyz"

# get string length
s1_length = len(s1)
s2_length = len(s2)

# get length of a bigger string
length = s1_length if s1_length > s2_length else s2_length
result = ""

# reverse s2
s2 = s2[::-1]

# iterate string 
# s1 ascending and s2 descending
for i in range(length):
    if i < s1_length:
        result = result + s1[i]
    if i < s2_length:
        result = result + s2[i]

print(result)
Code language: Python (python)

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
def string_balance_test(s1, s2):
    flag = True
    for char in s1:
        if char in s2:
            continue
        else:
            flag = False
    return flag


s1 = "Yn"
s2 = "PYnative"
flag = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", flag)

s1 = "Ynf"
s2 = "PYnative"
flag = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", flag)
Code language: Python (python)

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
str1 = "Welcome to USA. usa awesome, isn't it?"
sub_string = "USA"

# convert string to lowercase
temp_str = str1.lower()

# use count function
count = temp_str.count(sub_string.lower())
print("The USA count is:", count)
Code language: Python (python)

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
input_str = "PYnative29@#8496"
total = 0
cnt = 0
for char in input_str:
    if char.isdigit():
        total += int(char)
        cnt += 1

# average = sum / count of digits
avg = total / cnt
print("Sum is:", total, "Average is ", avg)
Code language: Python (python)

Solution 2: Use regular expression

import re

input_str = "PYnative29@#8496"
digit_list = [int(num) for num in re.findall(r'\d', input_str)]
print('Digits:', digit_list)

# use the built-in function sum
total = sum(digit_list)

# average = sum / count of digits
avg = total / len(digit_list)
print("Sum is:", total, "Average is ", avg)Code language: Python (python)

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
str1 = "Apple"

# create a result dictionary
char_dict = dict()

for char in str1:
    count = str1.count(char)
    # add / update the count of a character
    char_dict[char] = count
print('Result:', char_dict)
Code language: Python (python)

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

str1 = "PYnative"
print("Original String is:", str1)

str1 = str1[::-1]
print("Reversed String is:", str1)Code language: Python (python)

Solution 2: Using the reversed() function

str1 = "PYnative"
print("Original String is:", str1)

str1 = ''.join(reversed(str1))
print("Reversed String is:", str1)Code language: Python (python)

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
str1 = "Emma is a data scientist who knows Python. Emma works at google."
print("Original String is:", str1)

index = str1.rfind("Emma")
print("Last occurrence of Emma starts at index:", index)Code language: Python (python)

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
str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)

# split string
sub_strings = str1.split("-")

print("Displaying each substring")
for sub in sub_strings:
    print(sub)
Code language: Python (python)

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

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
res_list = []
for s in str_list:
    # check for non empty string
    if s:
        res_list.append(s)
print(res_list)Code language: Python (python)

Solution 2: Using the built-in function filter()

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]

# use built-in function filter to filter empty value
new_str_list = list(filter(None, str_list))

print("After removing empty strings")
print(new_str_list)Code language: Python (python)

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.

import string

str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)

new_str = str1.translate(str.maketrans('', '', string.punctuation))

print("New string is ", new_str)Code language: Python (python)

Solution 2: Using regex replace pattern in a string

import re

str1 = "/*Jon is @developer & musician"
print("Original string is ", str1)

# replace special symbols with ''
res = re.sub(r'[^\w\s]', '', str1)
print("New string is ", res)
Code language: Python (python)

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
str1 = 'I am 25 years and 10 months old'
print("Original string is", str1)

# Retain Numbers in String
# Using list comprehension + join() + isdigit()
res = "".join([item for item in str1 if item.isdigit()])

print(res)Code language: Python (python)

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
str1 = "Emma25 is Data scientist50 and AI Expert"
print("The original string is : " + str1)

res = []
# split string on whitespace
temp = str1.split()

# Words with both alphabets and numbers
# isdigit() for numbers + isalpha() for alphabets
# use any() to check each character

for item in temp:
    if any(char.isalpha() for char in item) and any(char.isdigit() for char in item):
        res.append(item)

print("Displaying words with alphabets and numbers")
for i in res:
    print(i)
Code language: Python (python)

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 #
import string

str1 = '/*Jon is @developer & musician!!'
print("The original string is : ", str1)

# Replace punctuations with #
replace_char = '#'

# string.punctuation to get the list of all special symbols
for char in string.punctuation:
    str1 = str1.replace(char, replace_char)

print("The strings after replacement : ", str1)
Code language: Python (python)

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Comments

  1. ImageVaidik says

    September 7, 2025 at 12:24 pm

    # 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)

    Reply
  2. ImageVaidik says

    September 7, 2025 at 12:15 pm

    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”))

    Reply
  3. Imageharry says

    July 11, 2025 at 7:11 am

    # 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))

    Reply
  4. Imageharry says

    July 11, 2025 at 7:07 am

    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))

    Reply
  5. Imageharry says

    July 11, 2025 at 7:03 am

    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)))

    Reply
  6. Imageharry says

    July 11, 2025 at 6:38 am

    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}”)

    Reply
    • ImageRieri says

      July 26, 2025 at 9:58 pm

      I think u are right

      Reply
  7. ImageStella says

    May 27, 2025 at 6:46 am

    #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 !”)

    Reply
  8. ImageStella says

    May 27, 2025 at 6:45 am

    # 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 )

    Reply
  9. Imagehamta says

    April 20, 2025 at 8:49 pm

    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)

    Reply
  10. ImageOkbazghi says

    January 28, 2025 at 5:43 pm

    Exercise 1.A
    str1=”James”
    print(f'{str1[0]}{str1[len(str1)//2]}{str1[-1]}’)

    Reply
  11. Imagekarthik says

    July 3, 2024 at 6:59 pm

    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)

    Reply
  12. Imagefasulu says

    January 22, 2024 at 11:37 pm

    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

    Reply
    • ImageLokesh varma somula says

      June 9, 2024 at 6:08 am

      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]

      Reply
      • ImageLokesh varma somula says

        June 11, 2024 at 3:27 am

        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]

        Reply
      • ImageBogdan says

        October 4, 2024 at 11:47 am

        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.

        Reply
  13. Imagebigapple says

    January 11, 2024 at 1:54 pm

    # 17
    def stay_alnum(string):
    for item in string.split():
    if not(item.isalpha()) and not(item.isdigit()):
    print(item)

    Reply
    • Imagedlinhares says

      March 28, 2024 at 8:34 pm

      #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)

      Reply
  14. ImageWalker says

    December 4, 2023 at 10:56 am

    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)

    Reply
  15. Imagepanos says

    November 12, 2023 at 2:27 am

    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)

    Reply
  16. Imagepanos says

    November 12, 2023 at 1:31 am

    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}”)

    Reply
  17. Imagepanos says

    November 12, 2023 at 1:02 am

    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=”)

    Reply
  18. Imagepanos says

    November 7, 2023 at 1:11 am

    Exercise 1

    str1 = “James”

    for i in range(len(str1)):
    if i % 2 == 0:
    print(str1[i], end=””)

    Reply
    • Imagefasulu says

      January 21, 2024 at 6:04 pm

      This will produce answer for the word “Python” as “Pto, and “Strings” as “Srns”

      Reply
  19. ImageIrina says

    October 26, 2023 at 12:27 am

    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)

    Reply
  20. Imagem.Usman Momin says

    October 24, 2023 at 10:10 pm

    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)

    Reply
  21. ImageMillie says

    October 24, 2023 at 6:25 pm

    the 12th one can also be done by using
    n=str1.index(“Emma”)
    print(str1.index(“Emma”,n+1,len(str1)))

    Reply
  22. Imageऋषित रघुवंशी says

    October 10, 2023 at 1:22 am

    question2
    str1 = “auly”
    str2 = “kelly”
    middle = int(len(str1)/2)
    x=str1[:middle]+str2+str1[middle:]
    print(x)

    Reply
  23. Imageऋषित रघुवंशी says

    October 10, 2023 at 1:17 am

    Question2
    str1= “Auly”
    middle = int(len(str1)/2)
    str2= “kelly”
    print(str1[:middle],str2,str1[middle:])

    Reply
    • Imageऋषित रघुवंशी says

      October 10, 2023 at 1:23 am

      question4
      str1 = “auly”
      str2 = “kelly”
      middle = int(len(str1)/2)
      x=str1[:middle]+str2+str1[middle:]
      print(x)

      Reply
  24. ImageViswanath says

    September 25, 2023 at 11:26 am

    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’)

    Reply
  25. Imagehosein says

    August 23, 2023 at 3:30 am

    A1راه حل بسیار کوتاه و عالی برای سوال

    str1 = “Jemes”

    print(str1)

    res = str1[:: 2]

    print(“new string:”, res)

    Reply
    • ImageMohammad says

      December 20, 2023 at 7:47 am

      str=’james’
      print(“Original string is: “,str)
      res=str[0]+str[2]+str[-1]
      print(“New string is: “,res)

      Reply
  26. ImageRitabrata says

    June 14, 2023 at 8:32 pm

    Q.16 Using Regex.

    import re

    str1 = 'I am 25 years and 10 months old'

    res=re.findall('\d+',str1)
    str_val="".join(res)
    print(str_val)

    OUTPUT:
    2510

    Reply
  27. ImageRitabrata says

    June 14, 2023 at 8:27 pm

    Q.17 Using Regex.

    import re

    str1 = "Emma25 is Data scientist50 and AI Expert"
    res=re.findall('\w+\d+',str1)
    for val in res:
    print(val)

    OUTPUT:
    Emma25
    scientist50

    Reply
  28. ImageHabibur Rahman says

    May 29, 2023 at 12:57 am

    my solution of q15
    str1 = "/*Jon is @developer & musician"
    str = ''
    for i in str1:
    if i.isalnum() or i.isspace():
    str += i

    print(str)

    Reply
  29. ImageLeigh says

    April 21, 2023 at 8:28 pm

    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))

    Reply
  30. ImageAnurag says

    March 23, 2023 at 2:12 am

    Question 2

    str1 = input("Enter 1st word: ")
    str2 = input("Enter 2nd word: ")
    len1 = (len(str1))//2
    print(str1[0:len1]+str2+str1[len1:])

    Reply
  31. ImageAnurag says

    March 22, 2023 at 7:10 pm

    str1 = input("Enter 1st word: ")
    len1 = (len(str1))//2
    print(str1[len1-1:len2+2])

    Reply
  32. ImageMahesh Reddy says

    March 6, 2023 at 4:13 pm

    exercise 18:

    str1 = '/*Jon is @developer & musician!!'

    old="/ * @ & ! !"
    new="# # # # # #"

    print(str1.translate(str.maketrans(old,new)))

    Reply
  33. ImageMahesh Reddy says

    March 6, 2023 at 4:07 pm

    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))

    Reply
    • Imagemohammad basheer says

      August 18, 2023 at 8:41 pm

      if you have hundreds of punctuations it is hard to replace like this

      Reply
  34. Image0xAH says

    March 2, 2023 at 7:30 pm

    # 1B
    def exe(x):
    mid = int(len(x)/2)
    print(x[mid-1:mid+2])

    Reply
  35. Image0xAH says

    March 2, 2023 at 7:27 pm

    # 1A

    print(x[::int(len(x)/2)])

    Reply
  36. Imagekalai says

    February 8, 2023 at 12:35 pm

    question 1:
    a="james"
    a1=a[0]
    a2=a[2]
    a3=a[-1]
    b=a1+a2+a3
    print(b)

    Reply
  37. ImageNermen says

    October 17, 2022 at 5:00 pm

    Question 7 :

    s1 = "Yn"
    s2 = "PYnative"

    print(all(item in s2 for item in s1))

    Reply
    • ImageAbhishek says

      February 28, 2023 at 1:33 pm

      str1 = "PyNaTive"
      lowercase = ""
      uppercase = ""
      for char in str1:
      if char.islower():
      lowercase = lowercase + char
      else:
      uppercase = uppercase + char

      result = lowercase + uppercase
      print(result)

      Reply
  38. Imagevini1955 says

    October 10, 2022 at 2:10 am

    Exercise 4:

    def lower_first(str1):
        for c in str1:
            if c == c.upper():
                str1 = str1[1:] + str1[0]
        print(str1)
    Reply
  39. ImageShubham Yadav says

    October 8, 2022 at 9:27 pm

    Solution for 1A.

    str1='james'
    print(str[0:2])
    Reply
    • ImageOnirom says

      January 28, 2023 at 5:13 pm

      str='james'
      print(str[0:6:2])

      Reply
  40. Imagelily fullery says

    October 1, 2022 at 3:37 pm

    question 17

    str1 = "emma25 is Data scientist and AI Expert30"
    m = str1.split()
    for i in m :
        for j in i:
            if(j.isalpha()):
                continue
            elif(j.isdigit()):
                print(i)
                break
    Reply
    • ImageVijayKumar says

      October 7, 2022 at 11:12 am

      m = []
      str1 = "Emma25 is Data scientist50 and AI Expert"
      s = str1.split()
      for i in s:
          if i.isalnum():
              m.append(i)
      print(m[0:4:3])
      Reply
    • ImageDJ says

      October 20, 2022 at 3:50 pm

      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

      Reply
  41. ImageAli says

    September 27, 2022 at 2:43 am

    (Pretty) Short Solution for Exercise 6:

    s1 = "Abc"
    s2 = "Xyz"
    for index in range(0,4):
        s3 = s1[index] + s2[-index-1]
        print(s3,end='')
    Reply
    • Imagemalleswari says

      December 7, 2022 at 1:03 pm

      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

      Reply
  42. ImageAmir says

    August 29, 2022 at 1:03 pm

    Short Solution of Exercise 14

    str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
    for i in str_list:
        if i=="":
            continue
        else:
            print(i)
    Reply
    • Imagechethan says

      October 4, 2022 at 4:33 pm

      None will come

      Reply
  43. ImageChinuogu David Enweani says

    August 21, 2022 at 9:01 pm

    This is an alternate solution for Exercise 5

     str1 = "P@#yn26at^&i5ve"
    print('Total counts of chars, digits and symbols')
    print()
    count = 0
    count2 = 0
    count3 = 0
    for i in str1:
    	if i.isalpha() == True:
    		count += 1
    	elif i.isdigit() == True:
    		count2 += 1
    	else:
    		count3 += 1
    		
    print('Chars = ', count)
    print('Digits = ', count2)
    print('Digits = ', count3) 
    Reply
    • ImageChinuogu David Enweani says

      August 21, 2022 at 9:10 pm

      This is another more concise alt solution to exercise 5

       str1 = "P@#yn26at^&i5ve"
      print('Total counts of chars, digits and symbols')
      print()
      count, count2, count3 = 0, 0, 0
      for i in str1:
      	if i.isalpha():
      		count += 1
      	elif i.isdigit():
      		count2 += 1
      	else:
      		count3 += 1
      		
      print('Chars = ', count, 'Digits = ', count2, 'Symbols = ', count3) 
      Reply
  44. Imagesruthy kannath says

    August 6, 2022 at 3:36 am

    s1 = "Abc"
    s2 = "Xyz"
    
    s3=''
    s2_rev = s2[::-1]
    for i in range(len(s1)):
        s3 += s1[i]
        s3 += s2_rev[i]
    print(s3)
    Reply
  45. Imageluke says

    August 2, 2022 at 10:23 pm

    Solution for exercise number 1, take into a count in case the length of the string when divided by 2 does not =0

    string = input("type string")
    str_len = len(string)
    sl = 0
    if str_len%2!=0:
        sl = str_len-1
        print("First letter is: ", string[0], " middle letter is: ", string[int(sl/2)], " last letter is: ", string[-1])
    elif str_len%2==0:
        sl = int(str_len)
        print("First letter is: ", string[0], " middle letter is: ", string[int(sl/2)], " last letter is: ", string[-1])
    Reply
  46. ImagePrakash says

    June 30, 2022 at 12:14 pm

    Exercise 3:

    def mix_string(s1, s2):
        print('Original String: ', s1, s2)
        first_s1 = s1[0]
        last_s1 = s1[-1]
        l1 = int(len(s1)/2)
        len1 = len(s1)
        if len1 % 2 == 0:
            mid_s1 = s1[l1 - 1]
        else:
            mid_s1 = s1[l1 - 0]
        first_s2 = s2[0]
        last_s2 = s2[-1]
        l2 = int(len(s2)/2)
        len2 = len(s2)
        if len2 % 2 == 0:
            mid_s2 = s2[l2 - 1]
        else:
            mid_s2 = s2[l2 - 0]
        final_string = first_s1 + first_s2 + mid_s1 + mid_s2 + last_s1 + last_s2
        return final_string
    
    print('Mix String: ', mix_string("America", "Japan"))

    Output:

    Original String:  America Japan
    Mix String:  AJrpan
    Reply
  47. ImagePrakash says

    June 30, 2022 at 10:36 am

    def append_mid(s1 , s2):
    
        mid = int(len(s1)/2)
        x1 = s1[:mid]
        x2 = s1[mid:]
        x = x1 + s2 + x2
        return x
    
    print( append_mid("Ault" , "Kelly"))

    Output:

    AuKellylt
    Reply
  48. ImageSwati Sharma says

    June 21, 2022 at 5:03 am

    for exercise 17:

    str1 ="Emma25 is Data scientist50 and AI Expert"
    my_list=[]
    temp=str1.split()
    for i in temp:
        flagd=False
        flaga=False
        for char in i:
            if char.isalpha():
                flaga=True
            if char.isdigit():
                flagd=True
        if flaga==True and flagd==True:
            my_list.append(i)
    print(my_list)
    Reply
    • ImageSasidhar Puthineedi says

      August 24, 2022 at 11:33 am

      #Optimize using break statement in inner for loop:
      
      str1 ="Emma25 is Data scientist50 and AI Expert"
      my_list=[]
      temp=str1.split()
      for i in temp:
          flagd=False
          flaga=False
          for char in i:
              if char.isalpha():
                  flaga=True
              if char.isdigit():
                  flagd=True
              if flaga and flagd:
                  my_list.append(i)
                  break
      print(my_list)
      Reply
    • Imagelily fullery says

      October 1, 2022 at 3:35 pm

      hey, thanks your code helped me solve this question.
      please have a look at how I modified ur code, and it optimized

      str1 = "emma25 is Data scientist and AI Expert30"
      m = str1.split()
      for i in m :
          for j in i:
              if(j.isalpha()):
                  continue
              elif(j.isdigit()):
                  print(i)
                  break
      Reply
    • Imagelily fullery says

      October 1, 2022 at 3:36 pm

      str1 = "emma25 is Data scientist and AI Expert30"
      m = str1.split()
      for i in m :
          for j in i:
              if(j.isalpha()):
                  continue
              elif(j.isdigit()):
                  print(i)
                  break
      Reply
    • ImageMahendra says

      May 28, 2025 at 6:39 pm

      Very good champ

      Reply
  49. Imagekalyan says

    June 14, 2022 at 3:18 pm

    s1 = "Ault"
    s2 = "Kelly"
    print(s1[0]+s2[0]+s1[2]+s2[2]+s1[-1]+s2[-1])

    ex 3 answer

    Reply
    • Imageram mote says

      June 20, 2022 at 12:55 pm

      Q 01:

      str2 = "JaSonAy"
      for i in range(len(str2)//2):
          y=str2[i:i+3]
      print(y)
      Reply
  50. Imagekalyan says

    June 14, 2022 at 3:14 pm

    s1 = "Ault"
    s2 = "Kelly"
    print(s1[:2]+s2[::]+s1[2:])

    add string s2 in middle of s1 string

    Reply
  51. ImageSinaJ says

    May 27, 2022 at 7:23 pm

    for exercise 7:

    s1 = "Yn"
    s2 = "PYnative"
    print(bool(s2.count(s1)))
    s1 = "Ynf"
    s2 = "PYnative"
    print(bool(s2.count(s1)))
    Reply
    • Imagelily fullery says

      September 30, 2022 at 12:07 am

      flag = True
      s1 = "Ynf"
      s2 = "PYnative"
      for i in s1:
          if(i in s2):
              continue
          else:
              flag = False
              print(flag)
      print(flag)
      Reply
      • Imagelily fullery says

        September 30, 2022 at 12:13 am

        please delete my previous reply

        s1 = "Ynf"
        s2 = "PYnative"
        a = 0 
        for i in s1:
            if(i not in s2):
                print(False)
                break
            elif(i in s2):
                a = a + 1
        if(len(s1)==a):
            print(True)
        Reply
  52. ImageAlvin says

    May 5, 2022 at 1:58 pm

    for number 14

    s1 = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
    while "" in s1:
        s1.remove("")
    print(s1)
    Reply
    • ImageAlvin says

      May 5, 2022 at 2:00 pm

      i forgot to add s1.remove(None) though

      Reply
  53. ImageArnav saini says

    April 14, 2022 at 9:56 pm

    Alternate solution of Exercise 15: Remove special symbols/punctuation from a string

    s = "/*Jon is @developer & musician"
     
     for item in s:
         if item.isalnum()!=True and ord(item)!=32:
             continue
         else:
             print(item,end="")
    Reply
  54. ImageArnav saini says

    April 14, 2022 at 11:56 am

    s = "PYnative29@#8496"
    l=[]
    for item in s:
        if item.isnumeric()==True:
            l.append(item)
    print(l)
    l = list(map(int,l))
    print(sum(l))
    Reply
    • Imagebro says

      April 27, 2022 at 3:56 am

      Can you pleas explain to me this code

      Reply
    • ImageVijayKumar says

      September 28, 2022 at 3:19 pm

      str1 = "PYnative29@#8496"
      m = []
      sum = 0
      for i in str1:
          if i.isdigit():
              m.append(i)
              sum = sum+int(i)
      print(sum/6)
      Reply
  55. ImageRohit Chandoriya says

    March 21, 2022 at 2:26 pm

    For Problem 16

    
    num1=input("Enter the starting number: ")
    #num2=input("Enter the starting number: ")
    #num1=[1,2,300,'',4,5,67,8,81,89,9,100,'',]
    
    
    #num2=[]
    def flo(a):
        num2=[]
        for word in a:
            if word.isdigit():
                num2.append(word)
        x=''.join(num2)
        print(x)
    
    print(flo(num1))
    Reply
  56. ImageRishikesh Shah says

    March 21, 2022 at 12:23 pm

    Q 15

     import re
    str1 = "/*John is @developer & musician"
    new_str = ''
    regex = re.compile('[@_!#$%^&*()?/\|}{~:]')
    for i in str1:
        if regex.search(i) == None:
            new_str = new_str + i
    print(new_str)
    Reply
  57. ImageVyom says

    March 1, 2022 at 2:05 am

    Example-18

    str1 = '/*Jon is @developer & musician!!'
    str2=list(split(str1))
    lt=['/','*','@','&','!']
    for i in range (len(lt)):
        str1=str1.replace(lt[i],'#')
    print(str1)
    Reply
    • ImageRishikesh Shah says

      March 22, 2022 at 12:07 pm

      Ex- 18

       import re
      str1 = "/*John is @developer & musician"
      new_str = ''
      regex = re.compile('[@_!#$%^&*()?/\|}{~:]')
      for i in str1:
          if regex.search(i):
              new_str = new_str + '#'
          else:
              new_str = new_str + i    
      print(new_str)
      Reply
      • ImageUlvy says

        October 31, 2023 at 2:09 pm

        str1 = “/*Jon is @developer!@#,><"
        for i in str:
        if i not in specialSymbols:
        newStrList += i
        return newStrList
        print(removeSpecialSymbol(str1))

        Reply
  58. ImageOlasunkanmi says

    January 15, 2022 at 10:26 am

    Question 6 alternative solution:

     def mixed_srting(x, y):
                      new_y = y[::-1]
                      for char in range(len(y)):
                             u = x[char] + new_y[char]
                             print(u, end="')
     
    s1 = "Abc"
    s2 = "Xyz"
    mixed_string(s1, s2)
    
    		
    Reply
  59. ImageOlaniyi Peter Olasunkanmi says

    January 14, 2022 at 10:56 am

    Exercise 6

    S1 = "Abc"
    S2 = "Xyz"
    b = 0
    while b < len(s1):
            u = S2[::-1]
            x = S1[b] + S2[b]
            b += 1
            print(x, end="")
    Reply
  60. ImageHaarini R says

    December 30, 2021 at 3:54 pm

    Exercise 10:

    str1 = "Apple"
    def my_new_func(each_char):
         return each_char,str1.count(each_char)
    
    final_dict = dict(map(my_new_func,str1))
    print(final_dict)
    Reply
  61. ImageGiorgos says

    December 22, 2021 at 12:53 pm

    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?

    
    str1 = '/*Jon is @developer & musician!!'
    rep = "#"
    for i in str1:
        if not i.isalpha() and not i.isdigit():
            print(i)
            str2 = str1.replace(i, "#")
    
    str3 = str1.replace("@", "#")
    print(str2)
    print(str3)
    Reply
  62. ImagePrakash A says

    December 8, 2021 at 6:15 pm

    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])
    Reply
    • Imageprakash says

      December 8, 2021 at 6:17 pm

        
      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])
      
      
      Reply
      • ImagePreetam says

        March 7, 2022 at 3:29 pm

        str1 = "Emma25 is Data scientist50 and AI Expert"
        import re
        data = re.findall(pattern=r"(\w+\d)", string=str1)
        print(data)
        Reply
    • ImageGokul says

      January 10, 2023 at 9:15 pm

      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

      Reply
  63. ImageInbar says

    December 4, 2021 at 4:57 pm

    Q13:
    using list comprehension:

    str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
    new_list =[item for item in str_list if item]
    print(new_list)
    Reply
  64. ImageDanilo says

    November 18, 2021 at 3:43 pm

    Exercise 3

    s1 = "America"
    s2 = "Japan"
    
    # get middle index
    x, y = int(len(s1)), int(len(s2))
    
    # concatenate
    mixed_string = s1[0] + s2[0] + s1[x] + s2[y] + s1[-1] + s2[-1]
    
    print(mixed_string)
    Reply
  65. ImageDanilo says

    November 18, 2021 at 1:41 pm

    Exercice 1A

    str1 = "James"
    print("String is:", str1)
    print("New string is: ", str[0::2])
    Reply
  66. ImagePrem Varma says

    November 11, 2021 at 4:11 pm

    Exercise 3

    s1 = "America"
    s2 = "Japan"
    a = len(s1)//2
    b = len(s2)//2
    print(s1[0],s2[0],s1[a],s2[b],s1[-1],s2[-1])
    Reply
  67. Imagesama71 says

    October 25, 2021 at 7:26 pm

    Q15

    str1 = "/*Jon is @developer & musician"
    for char in str1:
        if not char.isalpha():
            str1 = str1.replace(char, ' ')
    print(str1)

    output:
    Jon is developer musician

    Reply
  68. ImageBaraa says

    September 23, 2021 at 11:38 pm

    Q9

    str1 = "English = 78 Science = 83 Math = 68 History = 65"
    
    str1 = str1.split()
    total =0
    avg = 0
    for num in str1:
      if num.isnumeric():
        num = int(num)
        total += num
        avg += 1
    print(total)
    print(total/avg)
    Reply
    • ImageOlasunkanmi says

      September 28, 2021 at 11:13 am

      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

      Reply
  69. ImageMazhar Khilji says

    September 1, 2021 at 4:48 pm

    Exercise 16:

    str1 = 'I am 25 years and 10 months old'
    
    for char in str1:
        if char.isdigit():
            print(char,end="")
    Reply
  70. Imageamani says

    August 9, 2021 at 12:44 am

    str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
    def verif(char):
          if char is not None :
                return char
    res = list(filter(verif, str_list))
    print(res)
    Reply
  71. ImageP. V. CHOWDARY says

    August 3, 2021 at 10:12 pm

     def counter(x):
        output={}
        for i in x:
            output[i]=x.count(i)
        return output
    counter(str1)
    Reply
  72. ImageP. V. CHOWDARY says

    August 3, 2021 at 9:47 pm

    Q.9:

     def sum_average(x):
        sum=0
        count=0
        x=x.split()
        for i in range(0,len(x)):
            if x[i].isnumeric():
                count+=1
                sum=sum+int(x[i])
        avg=sum/count
        print(f'sum is {sum}\naverage is {avg}')
    
    sum_average(str1)
    Reply
  73. ImageP. V. CHOWDARY says

    August 3, 2021 at 9:23 pm

    Q.8:

     def usa_count(x):
        return x.lower().count('usa')
    usa_count(str1)
    Reply
    • Imageashokkumar says

      September 6, 2023 at 9:55 pm

      can you give the code without using count function or any other inbuilt pythons libraries

      Reply
  74. ImageP. V. CHOWDARY says

    August 3, 2021 at 8:28 pm

     def isbalance(x,y):
        output=True
        for i in x:
            if i in y:
                continue
            else:
                output=False
        return output
    Reply
  75. ImageChowdary P V says

    August 1, 2021 at 9:40 pm

     def string_generator(x,y):
        a=[i for i in x]
        b=[j for j in y]
        b.reverse()
        c=[]
        for k in range(0,len(a)):
            for l in range(0,len(b)):
                if k==l:
                    c.append(a[k])
                    c.append(b[l])
        print(''.join(c))
    string_generator('Abc','Xyz')
    Reply
  76. ImageP. V. CHOWDARY says

    August 1, 2021 at 7:44 pm

    Question-5:

     def counter(x):
        digits=0
        chars=0
        symbols=0
        spaces=0
        for i in x:
            if i.isalpha():
                chars+=1
            elif i.isnumeric():
                digits+=1
            elif i.isspace():
                spaces+=1
            else:
                symbols+=1
        print(f'Chars={chars}\nDigits={digits}\nSymbols={symbols}\nSpaces={spaces}')
    counter(s)#function calling

    Output:

    Chars=8
    Digits=3
    Symbols=4
    Spaces=0
    Reply
  77. ImageP.Raja Chowdary Polepalli says

    July 21, 2021 at 1:57 pm

    Exercise:4

     def string_manipulator(x):
           list1=[i for i in x if i==i.lower()]
           list2=[j for j in x if j==j.upper()]
           list3=list1 + list2
           print("".join(list3))
    Reply
  78. ImageRaja Chowdary Polepalli says

    July 21, 2021 at 1:24 pm

    Exercise:3

    def new_string(x,y):
        if len(x)%2 != 0 and len(y)%2 !=0:
            list1=[i for i in x]
            mid_val1 = list1.pop(len(list1) // 2)  #first ,we have to pop the middle value before popping 1st and last values
            first_val1=list1.pop(0)
            last_val1=list1.pop()
            list2 = [i for i in y]
            mid_val2 = list2.pop(len(list2) // 2)
            first_val2 = list2.pop(0)
            last_val2 = list2.pop()
            list3=[first_val1,first_val2,mid_val1,mid_val2,last_val1,last_val2]
        print("".join(list3))
    new_string(s1, s2)
    Reply
  79. ImageRaja Chowdary Polepalli says

    July 21, 2021 at 12:38 pm

    Exercise 2:

    s1 = "Ault"
    s2 = "Kelly"
    
    def new_string(x,y):
        list=[i for i in x]
        list.insert(len(x)//2,y)
        print(''.join(list))
    new_string(s1,s2)

    Output: AuKellylt

    Reply
    • ImageRishikesh Shah says

      March 16, 2022 at 11:04 am

      Exercise 2:

      
      s1 = "Ault"
      s2 = "Kelly"
      # expected output AuKellylt
      s3 = s1[0:len(s1)//2] + s2 + s1[-len(s1)//2:]
      print(s3)
      Reply
  80. ImageRaja Chowdary Polepalli says

    July 21, 2021 at 12:14 pm

    Question 1:

    def middle_three(x):
        n=len(x)//2-1
        return x[n:n+3]
    middle_three("JhonDipPeta") # 'Dip'
    middle_three("JaSonAy") # 'Son'
    Reply
  81. ImageSubin jerin says

    July 20, 2021 at 11:03 pm

    Anyone explain Q2 , I can’t understand that …? Pls help me

    Reply
    • ImageRaja Chowdary Polepalli says

      July 21, 2021 at 12:39 pm

      Exercise 2:

      s1 = “Ault”
      s2 = “Kelly”
      
      def new_string(x,y):
      list=[i for i in x]
      list.insert(len(x)//2,y)
      print(”.join(list))
      new_string(s1,s2)

      Output: AuKellylt

      Reply
  82. ImageMeghna says

    July 9, 2021 at 4:28 pm

    Q6 Alternate Solution

    def mixString(s1,s2):
      lengthS1 = len(s1)
      lengthS2 = len(s2)
      length  = lengthS1 if lengthS1 < lengthS2 else lengthS2 
      resultString=""
      for i in range(length):
        resultString=resultString+s1[i]+s2[-(i+1)]
      if i < lengthS1-1 :
        resultString=resultString+s1[i+1:]
      elif i < lengthS2-1:
        resultString=resultString+s2[i-1:-(lengthS2)-1 :-1]
      print(resultString)
      
    s1 = "Abcjjjj"
    s2 = "Xyzss"
    mixString(s1, s2)
    Reply
  83. ImageKaryse says

    July 8, 2021 at 9:13 am

    Wow, where have you been all my life? Thank you ???? You have made the world a better place.

    Reply
    • ImageNarendra Yadav says

      July 14, 2021 at 12:23 pm

      17.

      str1 = "Emma25 is Data scientist50 and AI Expert"
      isAlnum = []
      temp = str1.split()
      # print(temp)
      
      for data in temp:
      	if not data.isalpha():
      		isAlnum.append(data)
      output = ' '.join(isAlnum)
      print(output)
      Reply
      • ImageDanilo says

        December 9, 2021 at 2:01 pm

        I like the way you put it.
        I would suggest the code ends like this to match the expected output.

        
        str1 = "Emma25 is Data scientist50 and AI Expert"
        isAlnum = []
        temp = str1.split()
        # print(temp)
        
        for data in temp:
        	if not data.isalpha():
        		isAlnum.append(data)
        # output = ' '.join(isAlnum)
        
        for item in isAlnum:
            print(item)
        Reply
  84. ImageMeghna says

    July 6, 2021 at 9:54 pm

    Question 1
    with string as user input and length and odd length checking

    def getMiddleThreeChars(sampleStr):
      middleIndex = int(len(sampleStr) /2)
      print("Original String is", sampleStr)
      middleThree = sampleStr[middleIndex-1:middleIndex+2]
      print("Middle three chars are", middleThree)
    str1=input("enter a string of odd length greater than 7  ")
    str1=str1.strip()
    length=len(str1)
    while ((length < 7) or ((length%2) == 0)):
      str1=input("enter a string of odd length greater than 7")
      str1=str1.strip()
      length=len(str1)
    getMiddleThreeChars(str1)
    Reply
  85. ImageSoe Wai Yan Aung says

    April 1, 2021 at 10:08 pm

    For Q 17

    
    str1 = "Emma25 is Data scientist50 and AI Expert"
    for i in str1.split(' '):
        if not i.isalpha() and not i.isnumeric():
            print(i)
    Reply
    • ImageTushar says

      April 24, 2022 at 5:09 pm

      Thanks awesome way brilliant thinking!!

      Reply
  86. ImageRenegade says

    March 27, 2021 at 6:30 am

    Alternative for Q. 13

    def display(given):
    
      for i in given:
        replace = given.replace("-", "\n")
      print(replace)
    
    str = "Emma-is-a-data-scientist"
    display(str)
    Reply
  87. ImageAttiya says

    March 16, 2021 at 12:11 am

    Another solution for question 4:

    str1 = 'PyNaTive'
    x = len(str1)
    
    for y in range(x):
        if str1[y].islower() == True:
            print(str1[y],end='')
    
    for i in range(x):
        if str1[i].isupper() == True:
            print(str1[i],end='')
    Reply
  88. ImageSat says

    February 25, 2021 at 3:35 pm

    For, Question 6,

    s1 = "ABC"
    s2 = "XYZ"
    list1 = list(s1)
    list2 = list(s2[::-1])
    result = "".join(["".join(list(i)) for i in zip(list1, list2)])
    print(result)
    Reply
  89. Imagesatheesh says

    February 17, 2021 at 7:59 pm

    For Question 15: (could be a simple solution)

    str1 = "/*Jon is @developer$ &musician"
    result = []
    for i in str1:
        if i.islower() or i.isupper() or i == " ":
            result.append(i)
    print("".join(result))
    Reply
  90. ImageHT says

    January 29, 2021 at 3:05 am

    another solution to question 18:

    
    import re
    str2 = re.sub(r"[^\w\s]", "#", str1)
    print(str2)
    Reply
  91. ImageHT says

    January 29, 2021 at 2:36 am

    another solution to question 16

    
    import re
    str2 = re.sub(r"[^\d]", "", str1)
    print(str2)
    Reply
  92. ImageFarish says

    January 28, 2021 at 9:05 am

    I Just Wanna Know, Is this method is Correct or Not

    # Question 1

    str1 = "Jhon#Dip#Peta"
    x=str1.split('#')
    print(x)
    print(x[1])
    Reply
  93. ImageHT says

    January 28, 2021 at 12:51 am

    Another solution to question 7:

    
    def string(s1,s2):
        set1 = set(s1)
        set2 = set(s2)
        result = set1.issubset(set2)
        return result
    
    Reply
    • ImageRishikesh Shah says

      March 17, 2022 at 11:51 am

      Exercise 7

      
      def fun_balanced_str(s1, s2):
          length_s1 = len(s1)
          length_s2 = len(s2)
          counter = 0    
      
          if length_s1 > length_s2:
              length_big = length_s1
              length_small =length_s2
          else:
              length_big = length_s2
              length_small= length_s1
      
          for i in range(length_small):
              for j in range(length_big):
                  if s1[i] == s2[j]:                
                      counter += 1          
              
          if counter >= length_small:
              print(True)
          else:
              print(False)
      
      fun_balanced_str("Ynf", "PYnative")
      Reply
  94. ImageKhanyi says

    January 15, 2021 at 1:06 am

    Another solution to question 1

    str1 = "JaSonAy"
    str2 = "JhonDipPeta"
    
    hello = str1[2:5]
    bye = str2[4:7]
    print(hello)
    print(bye)
    Reply
  95. ImageRajkumar says

    January 11, 2021 at 1:33 pm

    A solution to question 14

    str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
    
    while '' in str_list:
        str_list.remove('')
    print(str_list)
    Reply
    • ImageRishikesh Shah says

      March 21, 2022 at 11:56 am

      
      str_list = ["Emma", "jon", "", "Kelly", None, "Eric", ""]
      print("Original list of string", str_list)
      new_list = []
      
      for i in str_list:
          if '' != i:    
              new_list.append(i)       
      
      print("After removing empty strings", new_list)
      Reply
  96. ImageRajkumar says

    January 7, 2021 at 10:59 am

    A solution to Question 5

    str1 = "P@#yn26at^&i5ve"
    lower = []
    upper = []
    digits = []
    symb = []
    
    for letters in str1:
        if letters.islower():
            lower.append(letters)
        elif letters.isupper():
            upper.append(letters)
        elif letters.isdigit():
            digits.append(letters)
        else:
            symb.append(letters)
    result = (''.join(lower+upper+digits+symb))
    print('Aligned String: ',result)
    print('No. of lower case :', len(lower))
    print('No. of upper case :', len(upper))
    print('No. of digits     :', len(digits))
    print('No. of Spl symbols:', len(symb))
    Reply
  97. ImageAdham Jubran says

    January 6, 2021 at 9:14 pm

    The solution to Question 10

    str1 = "Apple"
    
    adict = {char : str1.count(char) for char in str1}
    
    print(adict)
    Reply
  98. ImageAdham Jubran says

    January 6, 2021 at 8:56 pm

    The solution to Question 9

    str1 = "English = 78 Science = 83 Math = 68 History = 65"
    
    str1 = str1.split()
    str1 = str1[2: :3]
    nSum = 0
    for i in str1:
        nSum+= int(i)
    print(nSum)
    Reply
  99. ImageAdham Jubran says

    January 6, 2021 at 8:38 pm

    The solution to Question 7

    s1 = "Yn"
    s2 = "PYnative"
    s3 = "Ynf"
    
    print(set(s1).issubset(set(s2)))
    print(set(s3).issubset(set(s2)))
    Reply
  100. ImageAdham Jubran says

    January 6, 2021 at 8:29 pm

    The solution to Question 6:

    s1 = "Abc"
    s2 = "Xyz"
    
    aset = set(s1 + s2)
    while aset:
        print(aset.pop(), end= '')
    Reply
  101. Imagesarika says

    January 4, 2021 at 12:44 pm

    A solution to question 3

    def add(s1,s2):
        a=int(len(s1)/2)
        b=int(len(s2)/2)
        c=s1[0]+s2[0]+s1[a:a+1]+s2[b:b+1]+s1[-1]+s2[-1]
        print(c)
    add("America","Japan")
    Reply
  102. ImageAmrita Mehta says

    December 30, 2020 at 10:18 am

    Question 3

    
    def name(s1,s2):
        new_name = s1[0]+s2[0]+s1[int(len(s1)/2)]+s2[int(len(s2)/2)]+s1[-1]+s2[-1]
        return new_name
    name("America","Japan")
    Reply
    • ImageAndyLeeParker says

      June 26, 2021 at 7:56 am

      Beautiful!

      Reply
  103. ImageRajkumar says

    December 24, 2020 at 5:36 pm

    Question 3

    def string(str1):
        
        for char1 in str1:
            if char1.islower():
                print(char1, end='')
        for char2 in str1:
            if char2.isupper():
                print(char2, end='')
    
    str1 = "PyNaTive"
    string(str1)
    Reply
  104. ImageRajkumar says

    December 24, 2020 at 4:17 pm

    Question 2

    s1 = "Ault"
    s2 = "Kelly"
    
    s3 = s1[:2]+s2[:]+s1[2:]
    print(s3)
    Reply
  105. ImageDarrell Wright says

    December 16, 2020 at 9:40 pm

    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.

    Reply
  106. ImageShwethaNagaraj says

    December 16, 2020 at 4:16 pm

    The answer of question no 12

    
    str1 = "Emma is a data scientist who knows Python. Emma woks at google."
    print("Last occurrence of Emma starts at index ",str1.rindex("Emma"))
    Reply
  107. ImageNik says

    December 10, 2020 at 8:08 am

    This is really helpful. Thanks

    from string import punctuation
    
    str1 = '/*Jon is @developer & musician!!'
    print("The original string is: ", str1)
    
    # Replace punctuations with #
    replace_char = '#'
    
    # Using string.punctuation to get the list of all punctuations
    # use string function replace() to replace each punctuation with #
    
    for char in punctuation:
        str1 = str1.replace(char, replace_char)
    
    print("The strings after replacement : ", str1)
    Reply
  108. Imagehemlata mahajan says

    November 3, 2020 at 6:17 pm

    q17:

    import re
    str1 = "Emma25 is Data scientist50 and AI Expert"
    str2=re.findall('\w+\d+',str1)
    p="\n".join(str2)
    print(p)
    Reply
    • Imageneha says

      November 26, 2020 at 9:34 am

      where is ques

      Reply
    • ImageDanilo says

      October 20, 2023 at 10:12 am

      Alternative:

      str1 = “Emma25 is Data scientist50 and AI Expert”
      for i in str1.split():
      if not i.isalpha():
      print(i)

      Reply
  109. ImageAishwary saxena says

    October 31, 2020 at 4:09 pm

    str1 = "Emma is a data scientist who knows Python. Emma works at google."
    count = 0
    for key,value in enumerate(str1):
        if value == 'E' and key > 0:
            print('Emma at index index:',(key))
    Reply
  110. ImageAishwary saxena says

    October 31, 2020 at 3:27 pm

    ques 9 better methods to use regex than the listed above

    str1 = "English = 78 Science = 83 Math = 68 History = 65"
    emails = re.findall('[0-9]+', str1)
    sumd = 0
    for email in emails:
        sumd += int(email)
    print(f"the sum is {sumd}")
    
    percentage = sumd / len(emails)
    print('average is:',percentage)
    Reply
  111. ImageAishwary saxena says

    October 30, 2020 at 2:15 pm

    MY WAY OF SOLVING QUESTION NUMBER 1

     str3 = input("enter the string:")
    print(str3)
    print("Write index.......")
    startin = int(input("ENTER START INDEX:"))
    endin = int(input("ENTER ENDING INDEX:"))
    res = str3[startin:endin]
    print(res) 
    Reply
  112. ImageAbdu says

    October 27, 2020 at 10:22 pm

    question 5

    chars = 0
    digits = 0
    symbol = 0
    
    str1 = "P@#yn26at^&i5ve"
    
    for x in str1:
        if x.isalpha():
            chars+=1
        elif x.isdigit():
            digits+=1
        else:
            symbol+=1
    
    
    print("chars: ",chars)
    print("digits: ",digits)
    print("symbol: ",symbol)
    Reply
  113. Imageur_bantyness says

    October 4, 2020 at 11:35 pm

    def middle(str_1):
        mid= None
    
        for i in range(0,len(str_1)-1):   #iterating from start index(0) to last index)
            mid = (0 + (len(str_1)-1) ) // 2   #finding the mid of the String
    
        return mid
    
    
    str_1 = "JaSonAy"
    op = middle(str_1)
    
    print("the mid char are:{}{}{}".format(str_1[op-1],str_1[op],str_1[op+1])) # placing them using .format()
    Reply
  114. ImageNerdAlert says

    October 4, 2020 at 9:03 am

    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.

    word1 = "abcdefih"
    word2 = "xyzg"
    str1 = word1[0]+word2[-1]
    l1 = word1[1:]  # bcdefih
    l2 = word2[0:-1]  # xyz
    str2 = ""
    str3 = ""
    index = 0
    n = 1
    while True:
        if index < len(l1) and index < len(l2):
            str2 += l1[index]+l2[index-n]  #
            index += 1  # 2
            n += 2
        else:
            False
            break
    
    final = str1+str2
    res = list(word1+word2)
    for item in res:
        if item not in list(final):
            str3 += item
    final += str3
    
    print(final)
    Reply
    • ImageAnita says

      October 22, 2020 at 1:49 am

       
      def mixString(s1, s2):
          newstr = ""
          length1 = int(len(s1))
          length2 = int(len(s2))
          length_min = min(length1, length2)
          length_max = max(length1, length2)
          for i in range(length_min):
              if i < length1:
                  newstr = newstr + s1[i]
              if i < length2:
                  newstr = newstr + s2[-i-1]
                  
          for i in range(length_min, length_max):
              if i < length1:
                  newstr = newstr + s1[i]
              if i < length2:
                  newstr = newstr + s2[i-length_min]
          print(newstr)
          
      mixString("xyzabce", "ABC")
      Reply
  115. ImageDMS KARUNARATNE says

    September 7, 2020 at 12:26 pm

    Exercise Question 18

    import re
    str1 = "/*Jon is @developer & musician"
    str2 = re.sub(r'[^\w\s]', '#', str1)
    print( str2)
    Reply
  116. ImageDMS KARUNARATNE says

    September 4, 2020 at 10:25 am

    Exercise Question 9:

    str1 = "English = 78 Science = 83 Math = 68 History = 65"
    strlist=[]
    digilist=[]
    total=0
    digicount=0
    digiav=0
    strlist=str1.split()
    for item in strlist:
        if item.isnumeric():
            digilist.append(item)
    for i in digilist:
        total+=int(i)
        digicount+=1
        digiav=float(total/digicount)
    print(total)
    print(digiav)
    Reply
    • Imageapurv says

      September 7, 2020 at 7:39 pm

      thanks a lot

      Reply
  117. ImageDMS KARUNARATNE says

    September 3, 2020 at 4:03 pm

    Exercise Question 7: String characters balance Test

    s1 = "Yn"
    s2 = "PYnative"
    counter=len(s1)
    cctr=0
    for chr in s1:
        if chr in s2:
           cctr+=1
    if counter==cctr:
        print("True")
    else:
        print("False")
    Reply
  118. ImageDMS KARUNARATNE says

    September 3, 2020 at 1:24 pm

    exercise-4

    str1 = "PyNaTive"
    
    for item in str1:
        if (item.islower()):
            print(item,end="")
    for item in str1:
        if (item.isupper()):
            print(item,end="")
    Reply
  119. ImageAkshata Gaekwad says

    August 30, 2020 at 5:58 pm

    
    def getMiddleThreeChars(sampleStr):
      middleIndex = int(len(sampleStr) /2)
      print("Original String is", sampleStr)
      start = middleIndex-1
      end = -start
      middleThree = sampleStr[start:end]
    
      print("Middle three chars are", middleThree)
      
    getMiddleThreeChars("JhonDipPeta")
    getMiddleThreeChars("Jasonay")
    Reply
  120. ImageGalbatrollix says

    August 13, 2020 at 10:55 pm

    Q12: Alternative solution with for loop and count() function.

    
    def where_last_Emma(string):
        for number in range(len(string)+1,0,-1):
            if string[number:].count("Emma") != 0:
                return number
    
    
    print(where_last_Emma("Emma is a data scientist who knows Python. Emma works at google."))
    Reply
  121. ImageGalbatrollix says

    August 13, 2020 at 10:51 pm

    Q12: Alternative solution

    
    def where_last_Emma(string):
        for number in range(len(string)+1,0,-1):
            if string[number:].count("Emma")!=0:
                return number
    
    print(where_last_Emma("Emma is a data scientist who knows Python. Emma works at google."))
    Reply
  122. ImageBhavya says

    August 13, 2020 at 5:19 pm

    incoming question 7.

    def balance_test(str1, str2):
        if str1 in str2:
            print("str1 and str2 are balances", True)
        else:
            print("str1 and str2 are not balanced", False)
    
    
    balance_test("ynz", "Pynative")

    By the way, bro this site is THE BEST for beginners like me.

    Reply
    • Imagebhavya says

      August 13, 2020 at 9:53 pm

      for question number 9

      def sum_and_average(english, science, math, history):
          sum = english + science + math + history
          average = (english + science + math + history) / 2
          print(f"The sum is",( sum ), "and average is",( average ), "of all the marks")
      
      
      sum_and_average(78, 83, 68, 65)

      can anyone please point out anything that I may have done wrong.

      Reply
  123. ImageHOKAISEIG says

    August 11, 2020 at 2:45 pm

    QUESTIONS 4 and 5
    why use split()?
    i found no purpose.
    is it to remove space ?

    Reply
    • ImageVishal says

      August 11, 2020 at 3:33 pm

      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().

      Reply
  124. ImageGalbatrollix says

    August 11, 2020 at 12:21 am

    Q6: I made an alternative solution that doesn’t require reversing one of the strings, and uses a while loop instead of for loop.

    
    def mixstring2(s1,s2):
        len1=len(s1)
        len2=len(s2)
        finalstring=""
        number=0
        while True:
            if number<len1:
                finalstring+= s1[number]
            if number=len2 and number>=len1:
                break
        return finalstring
    print(mixstring2("ABC", "XYZ"))
    Reply
    • ImageGalbatrollix says

      August 11, 2020 at 12:23 am

      So my solution was pasted incorrectly… Here is the correct version:

      
      def mixstring2(s1,s2):
          len1=len(s1)
          len2=len(s2)
          finalstring=""
          number=0
          while True:
              if number<len1:
                  finalstring+= s1[number]
              if number=len2 and number>=len1:
                  break
          return finalstring
      print(mixstring2("ABC", "XYZ"))
      Reply
      • ImageGalbatrollix says

        August 11, 2020 at 12:26 am

        For some reason I can’t post it correctly…
        this part is supposed to be between first and second if statement:

        
                if number<len2:
                    finalstring+= s2[-number-1]
                number+=1
        
        Reply
  125. ImageDalvir says

    July 29, 2020 at 6:12 pm

    Hello

    Solution for Q. 9

    str1 = "Welcome to USA. usa awesome, isn't it?"
    string = str1.lower().count("usa")
    print("The USA count is: ", string)
    Reply
    • ImageDalvir says

      July 29, 2020 at 6:15 pm

      Above solution is for Q8

      Reply
  126. ImageMark says

    July 26, 2020 at 10:48 pm

    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.

    Reply
    • ImageVishal says

      July 28, 2020 at 11:49 am

      You are right, Mark. I have updated the expected output

      Reply
  127. Imageshiva says

    July 15, 2020 at 8:47 pm

    Exercise Question 9

    word = "English = 78 Science = 83 Math = 68 History = 65"
    
    word_list = word.split()
    
    total_sum = 0
    subject_count = 0
    for marks in word_list:
        if marks.isdigit():
            total_sum+=int(marks)
            subject_count+=1
    print('sum is:\t', total_sum)
    print('Avg is:\t', (total_sum/subject_count))
    Reply
  128. ImageMike Mace says

    July 9, 2020 at 12:54 pm

    None of the answers to Q 4, including the solution given, produce the required answer
    i.e. aeiNPTvy

    Reply
    • ImageVishal says

      July 10, 2020 at 11:27 am

      Yes, it was mistakenly written I have removed the condition

      Reply
  129. ImageAswathi Nair says

    July 6, 2020 at 8:54 pm

    Answer for first could be;

    
    str1 = input("Enter the string: ") 
    n = len(str1)//2
    print(str1[n-1:n+2])
    Reply
  130. ImageAngshumaan Basumatary says

    June 25, 2020 at 10:11 am

    Q: 7 Alternative solution hope it helps to understand better.

     def stringBalanceCheck(a, b):
        if a in b:
            return True
        else:
            return False
    
    
    s1 = "yn"
    s2 = "Pynative"
    flag = stringBalanceCheck(s1, s2)
    print("s1 and s2 are balanced", flag)
    
    s1 = "ynf"
    s2 = "Pynative"
    flag = stringBalanceCheck(s1, s2)
    print("s1 and s2 are balanced", flag)
    
    Reply
  131. ImageSH Sourov says

    June 19, 2020 at 2:26 pm

    
    def twostr(s1,s2):
        midle = int(len(s1)/2)
        print(s1[0:midle-1]+" " + s2 + " " +s1[midle-1:len(s1)])
    twostr("Chrisdem","IamNewString")
    Reply
  132. ImageJeromeLille says

    June 18, 2020 at 7:28 am

    Hi,

    My solution for Q10:

    
    def count(str1):
        setstr1 = set(str1)
        dic = {}
        for letter in setstr1:
            dic[letter] = str1.count(letter)
        return dic
    dic = count("pynativepynvepynative")   
    print(dic)
    Reply
    • ImageDanilo says

      November 19, 2021 at 12:43 pm

      Question 5

      
      str1 = "P@#yn26at^&i5ve"
      char_list = []
      digit_list = []
      symbol_list = []
      for i in str1:
          if i.isalpha():
              char_list.append(i)
              chars = len(char_list)
          elif i.isdigit():
              digit_list.append(i)
              digits = len(digit_list)
          else:
              symbol_list.append(i)
              symbols = len(symbol_list)
      print("Total counts of chars, digits and symbols", "\n")
      print("Chars =", chars)
      print("Digits =", digits)
      print(Symbols =", symbols)
      Reply
  133. ImageJeromeLille says

    June 18, 2020 at 7:25 am

    Hi,

    My solution for Q9:

    
    def sumAndAverage(str1):
        sumNum = sum([int(s) for s in str1.split() if s.isnumeric()])
        countNum = len([int(s) for s in str1.split() if s.isnumeric()])
        print("Total Marks is:", sumNum, "Average is ", sumNum / countNum)
    
    sumAndAverage("English = 78 Science = 83 Math = 68 History = 65")
    Reply
  134. ImageJeromeLille says

    June 18, 2020 at 7:20 am

    Hi,

    My solution for Q5:

    
    def findDigitsCharsSymbols(inputString):
        charCount = len([i for i in inputString if i.isalpha()])
        digitCount = len([i for i in inputString if i.isdigit()])
        symbolCount = len(inputString) - charCount - digitCount
        print("Chars = ", charCount, "Digits = ", digitCount, "Symbol = ", symbolCount)
          
    inputString = "P@#yn26at^&i5ve"
    print("total counts of chars, digits,and symbols")
    Reply
  135. ImageJeromeLille says

    June 18, 2020 at 7:10 am

    Hi,
    My solution for Q4:

    
    inputStr = "PyNaTive"
    
    inputStr2 = [i for i in inputStr if i.islower()] + [i for i in inputStr if i.isupper()]
    
    print("\n arranging characters giving precedence to lowercase letters:")
    print(''.join(inputStr2))
    
    Reply
  136. Imageswagat kamthe says

    May 30, 2020 at 12:38 pm

    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")
    
    Reply
  137. ImageFaizan Ahmed says

    May 27, 2020 at 9:36 am

    Really Helpful thanks a lot

    Reply
  138. ImageSHINU says

    May 14, 2020 at 2:52 pm

    Q8 character count

    str1 = "Welcome to USA. usa awesome, isn't it?"
    count_char = str1.lower().count("usa")
    print(count_char)
    

    output : 2

    Reply
  139. ImageSHINU says

    May 14, 2020 at 2:50 pm

    str1 = "Welcome to USA. usa awesome, isn't it?"
    count_char = str1.lower().count("usa")
    print(count_char)
    
    Reply
  140. ImageNitish Tomar says

    May 4, 2020 at 11:13 am

    you should have used __contains__() function also

    Reply
  141. ImageNikhil K says

    April 28, 2020 at 9:43 pm

    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)
    
    Reply
  142. ImageNikhil K says

    April 28, 2020 at 8:42 pm

    Q8: simplest way.

    s1 = "Welcome to USA. usa awesome, isn't it?"
    s2 = "USA"
    print(s1.lower().count(s2.lower()))
    
    Reply
  143. ImageNikhil K says

    April 28, 2020 at 8:35 pm

    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)
    
    Reply
  144. ImageNikhil K says

    April 28, 2020 at 8:16 pm

    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)
    
    Reply
  145. ImageNikhil K says

    April 28, 2020 at 7:55 pm

    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)
    
    Reply
  146. ImageNikhil K says

    April 28, 2020 at 7:26 pm

    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)
    
    Reply
  147. ImageNikhil K says

    April 28, 2020 at 5:15 pm

    Question 3:

    s1 = "America"
    s2 = "Japan"
    print(s1[0]+s2[0]+s1[int(len(s1)/2)]+s2[int(len(s2)/2)]+s1[-1]+s2[-1])
    
    Reply
    • ImageAlec Nigh says

      June 8, 2020 at 12:45 am

      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!

      Reply
      • ImageDurga Sravanthi says

        October 27, 2020 at 12:32 pm

        middle_char = s1[(len(s1) / 2)] + s2[len(s2) /2]
        Reply
  148. ImageNikhil K says

    April 28, 2020 at 3:44 pm

    Q2: The simplest solution.

    s1 = "Chrisdem"
    s2 = "IamNewString"
    s3 = int(len(s1)/2)
    print(s1[:s3-1]+s2+s1[s3-1:])
    
    Reply
  149. ImageNikhil K says

    April 28, 2020 at 3:27 pm

    Q1:

    s1 = 'JhonDipPeta'
    s2 = 'Jasonay'
    mid1 = int(len(s1)/2)
    print(s1[mid1-1:mid1+2])
    mid2 = int(len(s2)/2)
    print(s2[mid2-1:mid2+2])
    
    Reply
    • ImageYogi says

      April 25, 2022 at 12:11 pm

      i like this answer as a beginner i am getting this quick and easy.

      Reply
  150. ImagePrakash P Sinha says

    April 14, 2020 at 10:11 pm

    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 .. 🙂

    Reply
    • ImageVishal says

      April 15, 2020 at 12:19 am

      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.

      Reply
  151. ImageAbduLLAH Zulfiqar says

    April 7, 2020 at 1:00 pm

    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.

    Reply
    • ImageVishal says

      April 8, 2020 at 2:55 pm

      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

      Reply
      • ImagePrakash P Sinha says

        April 15, 2020 at 12:26 am

        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.

        Reply
  152. Imagesomnath says

    March 14, 2020 at 10:57 am

    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                               #concatenate
    
    Reply
  153. ImageSeetharam says

    February 4, 2020 at 11:56 am

    Question: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]))
    
    Reply
  154. ImageEl Mehdi Qaos says

    January 25, 2020 at 5:41 am

    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])
    
    Reply
  155. ImageZlatko says

    November 23, 2019 at 8:46 pm

    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")
    
    Reply
  156. ImageWaqar says

    August 3, 2019 at 4:43 pm

    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])
    
    Reply
  157. ImageUday Kiran Reddy Pateel says

    August 1, 2019 at 6:30 pm

    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")
    
    Reply
  158. ImageBarry Ford says

    July 4, 2019 at 4:12 am

    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.

    Reply
  159. ImageBarry Ford says

    July 4, 2019 at 3:58 am

    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))
    
    Reply
  160. ImageVitaliy says

    June 20, 2019 at 8:12 pm

    Q10

    str1 = input("Input word : ")
     print({c : str1.count(c) for c in str1})
    
    Reply
  161. ImageTarun Verma says

    May 29, 2019 at 2:24 pm

    Question 6: Please don’t give complicated solutions to easy problems, when we can solve these by easy methods

    s1 = "Pynative"
    s2 = "Website"
    L1 = list(s1)
    L2 = list(s2)
    mix = ""
    for n in range(len(L1)):
      mix = mix + L1[0] + L2[-1]
      del(L1[0])
      del(L2[-1])
    print (mix)
    
    Reply
    • ImageVignesh says

      July 13, 2019 at 9:08 pm

      Your answer is right if both the string lengths are equal. Else it is coming as list index out of range.

      Reply
    • Imagesonali says

      July 31, 2020 at 2:34 pm

      bro please check your code, it has errors

      Reply
    • ImageAbdullah says

      January 3, 2023 at 1:35 pm

      🤔🤔

      Reply
  162. ImageBill Hardwick says

    May 17, 2019 at 3:36 pm

    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}
    
    Reply
  163. ImageBill Hardwick says

    May 17, 2019 at 3:18 pm

    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

    Reply
  164. ImageBill Hardwick says

    May 16, 2019 at 7:37 pm

    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

    Reply
  165. ImageBill Hardwick says

    May 16, 2019 at 7:34 pm

    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)
    
    Reply
    • ImageTarun Verma says

      May 29, 2019 at 2:25 pm

      s1 = "Pynative"
      s2 = "Website"
      mix = ""
      L1 = list(s1)
      L2 = list(s2)
      for n in range(len(L1)):
        mix = mix + L1[0] + L2[-1]
        del(L1[0])
        del(L2[-1])
      print (mix)
      
      Reply
  166. ImageBill Hardwick says

    May 16, 2019 at 6:34 pm

    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.

    Reply
    • ImageVishal says

      May 16, 2019 at 10:22 pm

      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.

      Reply
  167. ImageBill Hardwick says

    May 16, 2019 at 6:07 pm

    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:

    txt = 'PyNaTive'
    lst = list(txt)
    lst.sort(reverse=True)
    txt2 = ''.join(lst)
    print(txt2)
    

    yvieaTPN

    Reply
    • ImageBarry Ford says

      July 4, 2019 at 4:31 am

      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.

      Reply
    • ImageNvm says

      October 31, 2023 at 7:07 pm

      It does not match the expected output.

      Reply
  168. ImageBill Hardwick says

    May 16, 2019 at 5:54 pm

    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:

    def get_middle(x):
      return int((len(x) + 1) /2 - 1)
    s1 = 'playlet'
    s2 = 'heaps of iron'
    s3 = s1[0] + s1[get_middle(s1)] + s1[-1] + s2[0] + s2[get_middle(s2)] + s2[-1]
    print(s1)
    print(s2)
    print(s3)
    

    Output:

    playlet
    heaps of iron
    python

    Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement