PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python String Exercises: 35+ Coding Problems with Solutions

Python String Exercises: 35+ Coding Problems with Solutions

Updated on: June 13, 2026 | 235 Comments

As you know, strings are widely used to store textual data. To perform programming tasks in Python, a good understanding of string manipulation is essential.

This article provides 35+ Python String practice questions that focus entirely on string operations, manipulation, slicing, and string functions.

Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

  • All solutions have been fully tested on Python 3.
  • Interactive Learning: Use our Online Code Editor to solve these exercises in real time.
  • Also, Solve Python Exercises: 29 topic-wise exercises with over 800+ coding questions

Also Read:

  • Python String Quiz: MCQs to help you get familiar with Python Strings
  • Python String Interview Questions

Let us know if you have any alternative solutions. It will help other developers.

+ Table of Contents (38 Exercises)

Table of contents

  • Exercise 1. Create a string made of the first, middle, and last character
  • Exercise 2. Create a string made of the middle three characters
  • Exercise 3. Append new string in the middle of a given string
  • Exercise 4. Create a new string made of the first, middle, and last characters of each input string
  • Exercise 5. Reverse a given string
  • Exercise 6. Find the last position of a given substring
  • Exercise 7. Split a string on hyphens
  • Exercise 8. Find all occurrences of a substring in a given string by ignoring the case
  • Exercise 9. String characters balance test
  • Exercise 10. Vowel Counter
  • Exercise 11. Prefix/Suffix Check
  • Exercise 12. Swap Case
  • Exercise 13. Remove Whitespace
  • Exercise 14. N-th Character Removal
  • Exercise 15. String Partitioning
  • Exercise 16. Extract File Extension
  • Exercise 17. Lowercase First
  • Exercise 18. Count all letters, digits, and special symbols from a given string
  • Exercise 19. Create a mixed string using alternating characters
  • Exercise 20. Calculate the sum and average of the digits present in a string
  • Exercise 21. Count occurrences of all characters within a string
  • Exercise 22. Remove empty strings from a list of strings
  • Exercise 23. Remove special symbols/punctuation from a string
  • Exercise 24. Remove all characters from a string except integers
  • Exercise 25. Find words with both letters and numbers
  • Exercise 26. Replace each special symbol with # in the following string
  • Exercise 27. Palindrome Check
  • Exercise 28. Anagram Detector
  • Exercise 29. Unique Character Check
  • Exercise 30. Title Case Logic
  • Exercise 31. Remove Duplicate Characters
  • Exercise 32. Word Reversal
  • Exercise 33. Character Interleaving
  • Exercise 34. Longest Word
  • Exercise 35. Acronym Creator
  • Exercise 36. Word Frequency
  • Exercise 37. First Non-Repeating Character
  • Exercise 38. String Rotation Check

Exercise 1. Create a string made of the first, middle, and last character

Practice Problem: Write a program to create a new string made of an input string’s first, middle, and last characters.

Exercise Purpose: This exercise teaches the fundamentals of String Indexing. Accessing specific positions, especially the middle that requires calculating length, is a foundational skill for data parsing and text manipulation.

Given Input: str1 = "James"

Expected Output: Jms

Solution
str1 = "James"
print("Original String is", str1)

# Get first character
first_char = str1[0]

# Get middle character
# Calculate index by dividing length by 2
res = len(str1)
middle_index = int(res / 2)
mid_char = str1[middle_index]

# Get last character
last_char = str1[-1]

# Combine characters
res_str = first_char + mid_char + last_char
print("New String:", res_str)Code language: Python (python)

Explanation to Solution:

  • len(str1): This function calculates the total number of characters in the string.
  • int(res / 2): Since indices must be integers, we divide the length to find the center point. For “James” (length 5), 5/2 is 2.5, which truncates to index 2 (the character ‘m’).
  • str1[-1]: Python allows negative indexing. -1 is a convenient shorthand to grab the very last character regardless of how long the string is.

Exercise 2. Create a string made of the middle three characters

Practice Problem: Write a program to create a new string made of the middle three characters of an input string of odd length.

Exercise Purpose: This builds on indexing by introducing String Slicing. Slicing is a powerful Python feature that lets you extract entire “chunks” of data efficiently.

Given Input: str1 = "JhonDipPeta"

Expected Output: Dip

Solution
def get_middle_three_chars(str1):
    print("Original String is", str1)

    # Find middle index
    mi = int(len(str1) / 2)

    # Slice string from (mid - 1) to (mid + 2)
    res = str1[mi - 1:mi + 2]
    print("Middle three chars are:", res)

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

Explanation to Solution:

  • mi = int(len(str1) / 2): Finds the center point of the string.
  • str1[mi - 1 : mi + 2]: The syntax [start:end] extracts characters. We go one step back from the middle (mi-1) and two steps forward (mi+2).
  • Exclusive Range: In Python slicing, the end index is not included in the result. Therefore, mi + 2 ensure that the character at mi + 1 is the last one captured.

Exercise 3. Append new string in the middle of a given string

Practice Problem: Given two strings, s1 and s2, create a new string by appending s2 in the middle of s1.

Exercise Purpose: This exercise introduces String Partitioning and Concatenation. In programming, you often need to “inject” data into a template or modify strings at specific locations.

Given Input: s1 = "Ault" s2 = "Kelly"

Expected Output: AuKellylt

Solution
def append_middle(s1, s2):
    print("Original Strings are", s1, s2)

    # Find middle index of first string
    mi = int(len(s1) / 2)

    # Get character from 0 to middle index
    x = s1[:mi]
    # Get character from middle index to end
    y = s1[mi:]

    # Combine all three
    res = x + s2 + y
    print("After appending new string in middle:", res)

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

Explanation to Solution:

  • s1[:mi]: This slice captures everything from the start-up to the middle index.
  • s1[mi:]: This slice captures everything from the middle index to the very end.
  • x + s2 + y: Python uses the plus operator to “glue” strings together. By placing s2 between the two halves of s1, we effectively insert it into the center.

Exercise 4. Create a new string made of the first, middle, and last characters of each input string

Practice Problem: Given two strings, s1 and s2, create a new string from the first, middle, and last characters of each input string.

Exercise Purpose: This exercise practices Complex Concatenation. It requires multiple independent extractions and organizing them into a single result, common when generating IDs or codes from user data.

Given Input: s1 = "America" s2 = "Japan"

Expected Output: AJrpan

Solution
s1 = "America"
s2 = "Japan"

# Get first, middle and last character from first string
first_char = s1[0]
middle_char = s1[int(len(s1) / 2)]
last_char = s1[-1]

# Get first, middle and last character from second string
first_char2 = s2[0]
middle_char2 = s2[int(len(s2) / 2)]
last_char2 = s2[-1]

# Combine all
res = first_char + first_char2 + middle_char + middle_char2 + last_char + last_char2
print("New String:", res)Code language: Python (python)

Explanation to Solution:

  • Parallel Extraction: We perform the same logic on two different variables (s1 and s2).
  • Order of Operations: The concatenation res = ... follows the specific sequence requested.
  • String Immutability: Note that we aren’t changing s1 or s2; we are creating an entirely new string variable res to hold the combination.

Exercise 5. Reverse a given string

Practice Problem: Write a program to reverse a given string.

Exercise Purpose: Reversing a string is a classic logic-building exercise. In Python, this is most efficiently done via Slicing, demonstrating the language’s ability to manipulate sequences using “steps.” It is a prerequisite for solving problems like palindrome detection.

Given Input: str1 = "PYnative"

Expected Output: evitanYP

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

# Using string slicing
# The -1 step starts from the end and moves toward the beginning
str1 = str1[::-1]

print("Reversed String is:", str1)Code language: Python (python)

Explanation to Solution:

  • [::-1]: This is the “slicing” operator. The first two colons indicate we are taking the entire range of the string (from start to finish).
  • The -1 Step: The third value represents the increment. A negative value tells Python to traverse the string backward, effectively reversing the order of characters.

Exercise 6. Find the last position of a given substring

Practice Problem: Write a program to find the last index of the substring “Emma” in a given string.

Exercise Purpose: While the .find() method searches from the beginning of a string, the .rfind() method (Reverse Find) locates the most recent occurrence of a specified pattern. This functionality is essential when parsing file paths or URLs that require identification of the final delimiter.

Given Input: str1 = "Emma is a data scientist who knows Python. Emma works at google."

Expected Output: Last occurrence of Emma starts at index 43

Solution
str1 = "Emma is a data scientist who knows Python. Emma works at google."
print("Original String is:", str1)

# Find the last occurrence of "Emma"
last_index = str1.rfind("Emma")

print("Last occurrence of Emma starts at index:", last_index)Code language: Python (python)

Explanation to Solution:

  • str1.rfind("Emma"): This method scans the string from right to left. It identifies the starting index of the last instance of “Emma.”
  • Index Accuracy: Even though it searches from the right, the index returned is still calculated from the left (index 0), maintaining consistency with standard Python indexing.

Exercise 7. Split a string on hyphens

Practice Problem: Write a program to split a given string on hyphens and display each substring.

Exercise Purpose: This exercise introduces the concept of tokenization. Dividing strings into smaller components based on delimiters, such as commas, spaces, or hyphens, is a common technique for processing CSV files, logs, and user-entered lists.

Given Input: str1 = "Emma-is-a-data-scientist"

Expected Output:

Displaying each substring: 
Emma
is
a
data
scientist
Solution
str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)

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

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

Explanation to Solution:

  • str1.split("-"): This method breaks the string at every occurrence of the hyphen and returns a List of strings.
  • The Loop: Since the result is a list, we use a for loop to iterate through the list and print each individual “token” on a new line.

Exercise 8. Find all occurrences of a substring in a given string by ignoring the case

Practice Problem: Write a program to find the total count of the substring “USA” in a given string, ignoring the case (i.e., both “usa” and “USA” should be counted).

Exercise Purpose: This exercise addresses case normalization. In practical data science and web scraping applications, text data is frequently inconsistent. Converting all text to lowercase prior to processing is considered a standard best practice.

Given Input: str1 = "Welcome to USA. usa awesome, isn't it?"

Expected Output: The USA count is: 2

Solution
str1 = "Welcome to USA. usa awesome, isn't it?"
sub_string = "USA"

# convert both to lower case
temp_str = str1.lower()
count = temp_str.count(sub_string.lower())

print("The USA count is:", count)Code language: Python (python)

Explanation to Solution:

  • .lower(): This method creates a temporary version of the string where all letters are lowercase. This ensures that “USA”, “usa”, and “Usa” all look identical to the computer.
  • .count(): A built-in string method that returns the number of non-overlapping occurrences of a substring. By running this on the normalized version of the text, we get a case-insensitive count.

Exercise 9. String characters balance test

Practice Problem: Write a program to check if two strings are balanced. For example, strings s1 and s2 are balanced if all the characters in s1 are present in s2. The character’s position doesn’t matter.

Exercise Purpose: This exercise focuses on membership testing. This fundamental concept is utilized in data validation, such as verifying whether a password contains required characters or determining if a search query matches a database entry.

Given Input:

Case 1: s1 = "yn", s2 = "PyNative"
Case 2: s1 = "ynf", s2 = "PyNative"

Expected Output:

Case 1: True
Case 2: False
Solution
def string_balance_check(s1, s2):
    flag = True
    for char in s1:
        if char in s2:
            continue
        else:
            flag = False
            break
    return flag

s1 = "yn"
s2 = "PyNative"
print("Is s1 and s2 balanced:", string_balance_check(s1, s2))

s1 = "ynf"
s2 = "PyNative"
print("Is s1 and s2 balanced:", string_balance_check(s1, s2))Code language: Python (python)

Explanation to Solution:

  • for char in s1: We only need to iterate through the “test” string (s1) to see if its requirements are met by the source string (s2).
  • if char in s2: The in operator is a highly optimized way in Python to check for the existence of a substring or character.
  • break: This is an efficiency step. Once we find a single character that is not in s2, we don’t need to check the rest of the string; we already know it is unbalanced.

Exercise 10. Vowel Counter

Practice Problem: Write a program to count the total number of vowels (a, e, i, o, u) in a given string.

Given Input: str1 = "Hello World"

Expected Output: Vowel Count: 3

Solution
str1 = "Hello World"
vowels = "aeiouAEIOU"
count = 0

for char in str1:
    if char in vowels:
        count += 1

print("Vowel Count:", count)Code language: Python (python)

Explanation to Solution:

  • vowels = "aeiouAEIOU": We include both lowercase and uppercase to ensure the program is case-insensitive without needing extra methods.
  • if char in vowels: The in operator is a highly readable and efficient way to check for a match within a collection.
  • Increment Logic: Every time the condition is met, the count variable increases by 1.

Exercise 11. Prefix/Suffix Check

Practice Problem: Check if a given URL starts with “https” and ends with “.com”.

Exercise Purpose: This exercise teaches Boolean Validation. Methods like .startswith() and .endswith() are cleaner and less error-prone than manual slicing for verifying file formats, protocols, or naming conventions.

Given Input: str1 = "https://google.com"

Expected Output: Is valid URL: True

Solution
str1 = "https://google.com"

# Check both start and end conditions
is_secure = str1.startswith("https")
is_com = str1.endswith(".com")

if is_secure and is_com:
    print("Is valid URL: True")
else:
    print("Is valid URL: False")Code language: Python (python)

Explanation to Solution:

  • startswith(): Returns True if the string begins with the specified prefix.
  • .endswith(): Returns True if the string finishes with the specified suffix.
  • Logical and: This ensures the result is only True if both specific parts of the string are present, which is perfect for simple URL or filename validation.

Exercise 12. Swap Case

Practice Problem: Write a program to toggle the case of all characters in a string (uppercase becomes lowercase and vice versa).

Exercise Purpose: This demonstrates Case Transformation. Though simple, it is often used in search algorithms to normalize data or in text editors to provide “Toggle Case” functionality.

Given Input: str1 = "PyThOn"

Expected Output: pYtHoN

Solution
str1 = "PyThOn"

# Swap all cases
res = str1.swapcase()

print("Original:", str1)
print("Swapped :", res)Code language: Python (python)

Explanation to Solution:

  • .swapcase(): This method iterates through the string internally. If a character is A-Z, it converts it to a-z. If it’s a-z, it converts it to A-Z.
  • Non-Alphabetic Chars: Symbols and numbers are ignored by this method, leaving them unchanged and preventing data corruption.

Exercise 13. Remove Whitespace

Practice Problem: Remove every single space from a given string, including spaces between words.

Exercise Purpose: This highlights the difference between Trimming and Filtering. While .strip() only removes leading/trailing spaces, .replace() can reach inside a string to remove characters globally.

Given Input: str1 = " P y t h o n "

Expected Output: Python

Solution
str1 = " P y t h o n "

# Replace space with nothing
res = str1.replace(" ", "")

print("Cleaned string:", res)Code language: Python (python)

Explanation to Solution:

  • .replace(" ", ""): This method looks for every instance of the first argument (a space) and swaps it for the second argument (nothing).
  • Global Action: Unlike some other methods, .replace() affects the entire string, making it ideal for removing all instances of a specific “noisy” character.

Exercise 14. N-th Character Removal

Practice Problem: Write a program to remove the character at index i from a string.

Exercise Purpose: Since Python strings are Immutable (you can’t just delete a character at an index), this exercise teaches you how to “reconstruct” a string by skipping over a specific part.

Given Input: str1 = "Python", i = 2

Expected Output:

Pyhon (The character 't' at index 2 was removed)
Solution
str1 = "Python"
i = 2

# Slice from start to i (exclusive)
first_part = str1[:i]

# Slice from i+1 to the end
last_part = str1[i+1:]

# Combine
res = first_part + last_part

print("After removing index", i, ":", res)Code language: Python (python)

Explanation to Solution:

  • str1[:i]: This captures “Py” (indices 0 and 1). Index 2 is excluded because the “stop” value in a slice is exclusive.
  • str1[i+1:]: This captures “hon” (indices 3, 4, and 5), effectively jumping over the character at index 2.
  • Immutability Bypass: Because we cannot modify str1 directly, we create a new string res that simply doesn’t contain the character we wanted to get rid of.

Exercise 15. String Partitioning

Practice Problem: Use the .partition() method to split a string into three parts: the part before a separator, the separator itself, and the part after it.

Exercise Purpose: .split() is great for breaking a string into many pieces. .partition() is a specialized tool that always returns a 3-tuple. It is especially useful for parsing data like email addresses or key-value pairs where the separator needs to be preserved or accounted for.

Given Input: str1 = "username@company.com", sep = "@"

Expected Output: ('username', '@', 'company.com')

Solution
str1 = "username@company.com"

# Partition the string at the first '@'
res = str1.partition("@")

print("Original String:", str1)
print("Partitioned Result:", res)
# Accessing specific parts
print("Username:", res[0])Code language: Python (python)

Explanation to Solution:

  • The 3-Tuple: Unlike split(), which discards the separator, partition() keeps it as the middle element of the result.
  • Consistency: It always returns exactly three elements. This makes “unpacking” very safe: prefix, sep, suffix = str1.partition("@").
  • First Occurrence: If the separator appears multiple times, it partitions only at the first occurrence.

Exercise 16. Extract File Extension

Practice Problem: Given a filename as a string, extract only the file extension (e.g., .png or .pdf).

Exercise Purpose: This exercise teaches String Parsing. In software development, you need to validate file types before processing uploads. It helps you practice finding the last occurrence of a character (the dot) to handle files with multiple dots correctly (like archive.tar.gz).

Given Input: file_name = "report_final_v2.pdf"

Expected Output: pdf

Solution
file_name = "report_final_v2.pdf"

# Method 1: Using split and taking the last item
extension = file_name.split(".")[-1]

print("File Name:", file_name)
print("Extension:", extension)Code language: Python (python)

Explanation to Solution:

  • .split("."): This breaks the string into a list wherever a dot appears. For my.photo.jpg, the list is ['my', 'photo', 'jpg'].
  • [-1]: This index always grabs the very last item in the list, the extension.
  • Robustness: This logic works even if the filename has no dots (it returns the whole filename) or multiple dots.

Exercise 17. Lowercase First

Practice Problem: Write a program to arrange string characters such that all lowercase letters come first, followed by all uppercase letters.

Exercise Purpose: This exercise introduces Conditional Filtering and Reassembly. It’s a common pattern in data sorting: you need to group items by a specific property (in this case, “casing”) while preserving their relative order.

Given Input: str1 = "PyNaTive"

Expected Output: yaivePNT

Solution
str1 = "PyNaTive"
lower = []
upper = []

for char in str1:
    if char.islower():
        lower.append(char)
    else:
        upper.append(char)

# Join both lists
res = "".join(lower + upper)
print("Result:", res)Code language: Python (python)

Explanation to Solution:

  • char.islower(): A built-in check that returns True if a character is lowercase.
  • Two-Bucket Strategy: By separating the characters into two groups as we find them, we ensure that all “lowers” stay together and all “uppers” stay together.
  • "".join(...): This efficiently glues our two sorted groups back into a single final string.

Exercise 18. Count all letters, digits, and special symbols from a given string

Practice Problem: Write a program to count all letters, digits, and special symbols from a given string.

Exercise Purpose: This introduces Character Classification. Using built-in string methods like .isalpha() and .isdigit() is the standard way to validate user input and perform data cleaning.

Given Input: str1 = "P@#yn26at^&i5ve"

Expected Output:

Total counts of chars, digits, and symbols: Chars = 8 Digits = 3 Symbol = 4
Solution
def count_chars_digits_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 a special symbol
        else:
            symbol_count += 1

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

sample_str = "P@#yn26at^&i5ve"
print("total counts of chars, digits, and symbols")
count_chars_digits_symbols(sample_str)Code language: Python (python)

Explanation to Solution:

  • for char in sample_str: This loop visits every single character in the string one by one.
  • char.isalpha(): Returns True if the character is a letter (A-Z or a-z).
  • char.isdigit(): Returns True if the character is a number (0-9).
  • else block: Since every character must be either a letter, a number, or a symbol, anything that fails the first two checks is automatically counted as a symbol.

Exercise 19. Create a mixed string using alternating characters

Practice Problem: Given two strings, s1 and s2, create a third string made of the first char of s1, then the last char of s2, Next, the second char of s1 and the second-to-last char of s2, and so on. Any left-over chars go at the end of the result.

Exercise Purpose: This exercise sharpens your ability to handle Multiple Pointer Traversal. It makes you think about coordinating indices moving in opposite directions (forward through one string and backward through another).

Given Input: s1 = "Abc" s2 = "Xyz"

Expected Output: AzbycX

Solution
s1 = "Abc"
s2 = "Xyz"

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

# Use length of the bigger string
length = s1_length if s1_length > s2_length else s2_length
result = ""

# Reverse s2 to make it easier to pick characters from the end
s2 = s2[::-1]

# Iterate through the range
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)

Explanation to Solution:

  • s2[::-1]: This is a common Python trick to reverse a string using slicing. By reversing s2 first, we can simply pull characters from both strings using the same index i.
  • if i < s1_length: Since strings might have different lengths, these checks prevent “Index out of range” errors by ensuring the index exists before we try to access it.
  • Concatenation: Characters are appended to the result variable one by one in the specific alternating order required.

Exercise 20. Calculate the sum and average of the digits present in a string

Practice Problem: Given a string, run a loop to calculate the sum and average of the digits that appear in the string. Ignore all other characters.

Exercise Purpose: This combines Data Extraction with Arithmetic Operations. It demonstrates how to filter relevant data (numbers) out of a “noisy” string (letters and symbols) to perform calculations.

Given Input: str1 = "PYnative29@#8496"

Expected Output: Sum is: 38 Average is 6.33

Solution
str1 = "PYnative29@#8496"
total_sum = 0
cnt = 0

for char in str1:
    if char.isdigit():
        total_sum += int(char)
        cnt += 1

# average = sum / count of digits
avg = total_sum / cnt

print("Sum is:", total_sum, "Average is", avg)Code language: Python (python)

Explanation to Solution:

  • char.isdigit(): This filters the string, ensuring we only attempt to perform math on actual numeric characters.
  • int(char): Characters in a string are still “strings” even if they look like numbers. We must explicitly cast them to integers to perform addition.
  • Floating Point Division: In Python 3, the / operator automatically handles decimal values, providing the precise average.

Exercise 21. Count occurrences of all characters within a string

Practice Problem: Count the frequency of every character in a string and store the results in a dictionary.

Exercise Purpose: This exercise introduces Frequency Mapping using Dictionaries. Dictionaries are essential for counting and organizing data because they store unique “keys” (the characters) and associated “values” (their counts).

Given Input: str1 = "apple"

Expected Output: {'a': 1, 'p': 2, 'l': 1, 'e': 1}

Solution
str1 = "apple"

# Create an empty dictionary
char_dict = dict()

for char in str1:
    # Check if character is already in the dictionary
    if char in char_dict:
        char_dict[char] += 1
    else:
        # Add the character to the dictionary
        char_dict[char] = 1

print(char_dict)Code language: Python (python)

Explanation to Solution:

  • dict(): Initializes an empty collection to store our counts.
  • if char in char_dict: This checks if the character has been seen before.
  • Key-Value Logic: If it’s a new character, we initialize it at 1. If we’ve seen it before, we simply increment the existing count. This pattern is widely used in data analysis to determine the distribution of data points.

Exercise 22. Remove empty strings from a list of strings

Practice Problem: Given a list of strings, remove any empty strings or None values from it.

Exercise Purpose: This introduces Data Cleaning. Real-world datasets often have missing or empty values. Learning to filter lists is essential to prevent your program from crashing when processing empty data points.

Given Input: str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]

Expected Output: ['Emma', 'Jon', 'Kelly', 'Eric']

Solution
str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
print("Original list of strings:", str_list)

# use filter() to remove None and empty strings
# filter(None, sequence) removes all falsy values
new_str_list = list(filter(None, str_list))

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

Explanation to Solution:

  • filter(None, str_list): In Python, empty strings "" and the value None are considered “Falsy.” When filter is called with None as its first argument, it automatically discards everything that isn’t “Truthy.”
  • list(): Because filter returns a filter object (an iterator), we wrap it in list() to convert it back into a standard list format.

Exercise 23. Remove special symbols/punctuation from a string

Practice Problem: Write a program to remove all special symbols and punctuation from a given string.

Exercise Purpose: This exercise is a staple of Natural Language Processing (NLP). Before analyzing text like sentiment analysis, you must remove “noise” such as symbols and punctuation so the computer can focus on the words.

Given Input: str1 = "/*Jon is @developer & musician!!"

Expected Output: "Jon is developer musician"

Solution
import string

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

# Solution 1: Using a loop and isalnum()
new_str = ""
for char in str1:
    # Keep characters if they are letters/numbers or a space
    if char.isalnum() or char.isspace():
        new_str += char

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

Explanation to Solution:

  • char.isalnum(): This method checks if a character is either a letter or a number. If it’s a symbol (like *, @, or !), it returns False.
  • char.isspace(): We explicitly check for spaces; otherwise, the words would all get mashed together (e.g., “Jonisdevelopermusician”).
  • String Building: We start with an empty string and “build” the clean version character by character.

Or Use the regex in Python. See Python regex replace.

Exercise 24. Remove all characters from a string except integers

Practice Problem: Write a program to extract only the numeric digits from a mixed string and combine them into a single string.

Exercise Purpose: This is a core part of Data Extraction. Often when scraping web data or reading OCR text from images, you get strings like “Price: $25.00”. This exercise teaches you how to strip away the “noise” such as currency, labels, and spaces to get the raw numerical data for calculations.

Given Input: str1 = "I am 25 years and 10 months old"

Expected Output: 2510

Solution
str1 = "I am 25 years and 10 months old"
print("Original string is:", str1)

# Joining only the digits found in the string
res = "".join([item for item in str1 if item.isdigit()])

print("Resulting digits:", res)Code language: Python (python)

Explanation to Solution:

  • List Comprehension: The code [item for item in str1 if item.isdigit()] creates a temporary list containing only the characters that are numbers.
  • "".join(): This is the most efficient way to turn a list of characters back into a single string. It takes all the items in the list and “glues” them together using an empty string as the separator.
  • isdigit() Logic: This ensures that spaces, letters, and punctuation are entirely ignored

Exercise 25. Find words with both letters and numbers

Practice Problem: Write a program to find and print words from a string that contain both letters and numbers.

Exercise Purpose: This exercise focuses on Contextual Filtering. In cybersecurity or system administration, you often need to find “alphanumeric” strings like Product IDs (e.g., PROD123), license keys, or mixed-character usernames. It teaches you how to look for specific patterns within individual tokens.

Given Input: str1 = "Emma25 is Data scientist50 and AI Expert"

Expected Output:

Emma25
scientist50
Solution
str1 = "Emma25 is Data scientist50 and AI Expert"
print("The original string is:", str1)

# Split string into individual words
res = []
temp = str1.split()

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

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

Explanation to Solution:

  • str1.split(): This breaks the sentence into a list: ['Emma25', 'is', 'Data', ... ].
  • any() function: This is a clever Python tool. any(char.isalpha() for char in item) checks if at least one character in that specific word is a letter.
  • The and Logic: By requiring both an isalpha and an isdigit check to be true, we filter out words that are only letters (like “Data”) or only numbers.

Exercise 26. Replace each special symbol with # in the following string

Practice Problem: Write a program to replace every special symbol (punctuation) in a string with a specific character, like #.

Exercise Purpose: Vital for Data Sanitization. Before sending text to certain databases or file systems that can’t handle symbols like @ or &, you often need to “mask” them. It’s also a great introduction to the string module’s built-in constants.

Given Input: str1 = "/*Jon is @developer & musician!!"

Expected Output: ##Jon is #developer # musician##

Solution
import string

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

# Set the replacement character
replace_char = '#'

# Create a list of all punctuation symbols
punctuation = string.punctuation

for char in punctuation:
    str1 = str1.replace(char, replace_char)

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

Explanation to Solution:

  • import string: This module provides a pre-made string called string.punctuation, which contains all standard symbols like !"#$%&'()*+,-./:;<=>?@[\]^_{|}~.
  • str1.replace(char, replace_char): Inside the loop, we find every instance of a specific symbol and swap it for #.
  • Sequential Replacement: Since we are updating str1 within the loop (str1 = str1.replace(...)), each subsequent symbol is replaced until the string is completely sanitized.

Exercise 27. Palindrome Check

Practice Problem: Write a program to check if a string is a palindrome (reads the same forward and backward).

Exercise Purpose: The palindrome check is the “Hello World” of Algorithmic Logic. It teaches you how to compare a sequence against its own reflection. In real-world applications, this concept is used in DNA sequencing and data integrity verification.

Given Input: str1 = "radar"

Expected Output: Is Palindrome: True

Solution
def is_palindrome(s):
    # Normalize to lowercase to avoid case issues
    s = s.lower()
    # Compare string with its reverse
    return s == s[::-1]

print("Is 'radar' a palindrome?", is_palindrome("radar"))
print("Is 'Python' a palindrome?", is_palindrome("Python"))Code language: Python (python)

Explanation to Solution:

  • s[::-1]: This creates a reversed copy of the string.
  • s.lower(): Palindromes like “Racecar” would fail a standard check because “R” != “r”. Normalizing the case ensures the logic focuses only on the characters themselves.
  • Boolean Comparison: The == operator returns True if every character matches its corresponding character in the reversed version.

Exercise 28. Anagram Detector

Practice Problem: Write a program to check if two strings are anagrams (formed by rearranging the letters of another, such as “listen” and “silent”).

Exercise Purpose: This exercise teaches Canonical Forms. By sorting two different strings into a “standard” order (alphabetical), you can easily determine if they contain the exact same ingredients. This is a fundamental concept in data deduplication.

Given Input: s1 = "listen", s2 = "silent"

Expected Output: Are Anagrams: True

Solution
def check_anagram(s1, s2):
    # Sort both strings
    # sorted() returns a list of characters in alphabetical order
    return sorted(s1.lower()) == sorted(s2.lower())

s1 = "listen"
s2 = "silent"

if check_anagram(s1, s2):
    print(f"{s1} and {s2} are anagrams.")
else:
    print(f"{s1} and {s2} are NOT anagrams.")Code language: Python (python)

Explanation to Solution:

  • sorted(): This is the key. When you sort “listen”, you get ['e', 'i', 'l', 'n', 's', 't']. When you sort “silent”, you get the exact same list.
  • Comparison: If two strings have the same characters in the same quantities, their sorted lists will always be identical, making this the most efficient way to detect an anagram without complex loops.

Exercise 29. Unique Character Check

Practice Problem: Write a function to determine if a string has all unique characters. Return True if every character appears only once, otherwise return False.

Exercise Purpose: This introduces the concept of Sets. In Python, a set is an unordered collection that cannot contain duplicate items. Comparing the length of a string to the length of its “set version” is the most efficient way to check for uniqueness in O(n) time.

Given Input: str1 = "python"

str2 = "alphabet"

Expected Output:

"python" unique: True
"alphabet" unique: False
Solution
def is_unique(s):
    # A set only keeps unique elements
    char_set = set(s)
    return len(char_set) == len(s)

str1 = "python"
str2 = "alphabet"

print(f"'{str1}' unique: {is_unique(str1)}")
print(f"'{str2}' unique: {is_unique(str2)}")Code language: Python (python)

Explanation to Solution:

  • set(s): This operation scans the string and builds a collection of its unique characters. For “alphabet”, the set would be {'a', 'l', 'p', 'h', 'b', 'e', 't'} (the second ‘a’ is dropped).
  • Length Comparison: If the string had duplicates, the set will be shorter than the original string. If they are the same length, no characters were lost, meaning every character was unique.

Exercise 30. Title Case Logic

Practice Problem: Write a program to capitalize the first letter of every word in a sentence without using the built-in .title() method.

Exercise Purpose: This practice covers String Splitting and Indexing. While .title() exists, manually implementing it helps you understand how to isolate parts of a string, modify them, and rebuild the sentence. This is a common requirement in data transformation.

Given Input: str1 = "hello world from python"

Expected Output: Hello World From Python

Solution
str1 = "hello world from python"

# Split into words
words = str1.split()
result_words = []

for word in words:
    # Capitalize first char and add the rest
    capitalized = word[0].upper() + word[1:]
    result_words.append(capitalized)

# Join back into a sentence
res = " ".join(result_words)
print(res)Code language: Python (python)

Explanation to Solution:

  • word[0].upper(): This isolates only the first letter of the word to change its case.
  • word[1:]: This “slice” captures everything from the second character to the end, ensuring we don’t lose the rest of the word.
  • " ".join(...): This takes our list of modified words and stitches them back together with spaces in between.

Exercise 31. Remove Duplicate Characters

Practice Problem: Write a program to remove all duplicate characters from a string while keeping the remaining characters in their original order.

Exercise Purpose: This focuses on Order-Preserving Filtering. While a set() removes duplicates, it also ruins the order. This exercise teaches you how to use a loop and a “seen” tracker to clean data without scrambling it.

Given Input: str1 = "google"

Expected Output: gole

Solution
str1 = "google"
seen = set()
result = []

for char in str1:
    if char not in seen:
        result.append(char)
        seen.add(char)

res_str = "".join(result)
print("Original:", str1)
print("Cleaned :", res_str)Code language: Python (python)

Explanation to Solution:

  • The “Seen” Tracker: We use a set for seen because checking if char in seen It is extremely fast in Python.
  • Conditional Addition: The if char not in seen The check ensures that the second ‘o’ and the second ‘g’ in “google” are skipped.
  • Preserving Order: Because we iterate through the original string from left to right, our result list collects characters in the exact order they first appeared.

Exercise 32. Word Reversal

Practice Problem: Reverse the order of words in a given sentence, but keep the characters within the words in their original order.

Exercise Purpose: This clarifies the difference between Sequence Reversal and Character Reversal. It’s a standard interview question that tests your ability to manipulate lists of strings rather than just raw text.

Given Input: str1 = "Python is fun"

Expected Output: fun is Python

Solution
str1 = "Python is fun"

# 1. Split into list: ['Python', 'is', 'fun']
words = str1.split()

# 2. Reverse the list: ['fun', 'is', 'Python']
reversed_words = words[::-1]

# 3. Join back into a string
res = " ".join(reversed_words)

print(res)Code language: Python (python)

Explanation to Solution:

  • str1.split(): This turns the string into a list of “tokens.”
  • words[::-1]: Just like with strings, the [::-1] slice reverses the order of elements in a list.
  • Final Join: We use a space " " as the glue to turn the list back into a readable sentence.

Exercise 33. Character Interleaving

Practice Problem: Given two strings of equal length, merge them by alternating characters.

Exercise Purpose: This exercise introduces Parallel Iteration. In data science, you often need to merge two separate arrays of data (like names and IDs) into a single paired format. It teaches you how to coordinate multiple indices simultaneously.

Given Input: s1 = "ABC", s2 = "xyz"

Expected Output: AxByCz

Solution
s1 = "ABC"
s2 = "xyz"
res = ""

for i in range(len(s1)):
    res = res + s1[i] + s2[i]

print("Interleaved string:", res)Code language: Python (python)

Explanation to Solution:

  • range(len(s1)): This generates indices (0, 1, 2) that we can use for both strings since they are the same length.
  • Alternating Addition: In the first loop, i is 0, so we add s1[0] (‘A’) and s2[0] (‘x’). In the second loop, we add ‘B’ and ‘y’, and so on.
  • Manual Zip: While Python has a zip() function that does this more elegantly, doing it with a loop builds a stronger understanding of how indices work.

Exercise 34. Longest Word

Practice Problem: Write a program to find the longest word in a given sentence. If there is a tie, return the first one found.

Exercise Purpose: This exercise practices Comparison Logic and State Tracking. It’s a fundamental pattern in programming: iterating through a collection while keeping track of the “best” (or longest/largest) item found so far.

Given Input: str1 = "The quick brown fox jumps over the lazy dog"

Expected Output: Longest word: quick

Note: “brown” and “jumps” are also 5 letters, but “quick” appears first.

Solution
str1 = "The quick brown fox jumps over the lazy dog"

# Split string into a list of words
words = str1.split()
longest = ""

for word in words:
    # If current word is strictly longer than our record, update it
    if len(word) > len(longest):
        longest = word

print("Longest word:", longest)Code language: Python (python)

Explanation to Solution:

  • str1.split(): Converts the sentence into an iterable list.
  • State Tracking: By keeping the longest word in a variable outside the loop, we ensure we only need to pass through the list exactly once. This is O(n) efficiency.
  • Strict Comparison (>): Using “greater than” ensures that if two words have the same length, we keep the one that appeared first in the string.

Exercise 35. Acronym Creator

Practice Problem: Write a program to generate an acronym from a given phrase (e.g., “Random Access Memory” becomes “RAM”).

Exercise Purpose: This exercise focuses on String Transformation. It teaches you how to extract specific metadata (the first letter) from tokens and combine them into a new, condensed format.

Given Input: str1 = "Random Access Memory"

Expected Output: RAM

Solution
str1 = "Random Access Memory"

# Extract the first character of each word and uppercase it
acronym = "".join([word[0].upper() for word in str1.split()])

print("Acronym:", acronym)Code language: Python (python)

Explanation to Solution:

  • List Comprehension: [word[0] for word in str1.split()] is a concise way to create a list of just the first letters.
  • .upper(): This ensures the acronym is properly capitalized even if the input phrase was in lowercase.
  • .join(): Glues the individual letters together without any spaces.

Exercise 36. Word Frequency

Practice Problem: Count the occurrences of each word in a string and store the result in a dictionary.

Exercise Purpose: This is the word-level version of character counting. It introduces Frequency Mapping at scale, which underpins search engine indexing and “word cloud” generation.

Given Input: str1 = "apple banana apple cherry banana apple"

Expected Output: {'apple': 3, 'banana': 2, 'cherry': 1}

Solution
str1 = "apple banana apple cherry banana apple"
words = str1.lower().split()
word_count = {}

for word in words:
    # Get the current count (default to 0 if not found) and add 1
    word_count[word] = word_count.get(word, 0) + 1

print(word_count)Code language: Python (python)

Explanation to Solution:

  • .lower(): Normalizes the data so that “Apple” and “apple” are counted as the same word.
  • .get(word, 0): This is a pro-tip! It tries to find the word in the dictionary. If the word doesn’t exist yet, it returns 0 instead of crashing, allowing you to add 1 safely.
  • Dynamic Storage: The dictionary automatically grows as new, unique words are encountered.

Exercise 37. First Non-Repeating Character

Practice Problem: Find the first character in a string that does not repeat anywhere else.

Exercise Purpose: This exercise demonstrates Multi-Pass Algorithms. You cannot solve this in a single pass because you won’t know if a character repeats until you see the whole string. It teaches you to use a frequency map to guide a second traversal.

Given Input: str1 = "swiss"

Expected Output: w

Solution
def first_unique(s):
    counts = {}
    # First pass: count frequencies
    for char in s:
        counts[char] = counts.get(char, 0) + 1
    
    # Second pass: check order
    for char in s:
        if counts[char] == 1:
            return char
    return None

print("First unique in 'swiss':", first_unique("swiss"))Code language: Python (python)

Explanation to Solution:

  • Efficiency: This is an O(n) solution. We look at the string twice, which is much faster than checking every character and then scanning the rest of the string for its twin (O(n2)).
  • Why the second loop?: Dictionaries in modern Python preserve order, but looping through the string itself ensures we find the very first character that met our criteria in its original position.

Exercise 38. String Rotation Check

Practice Problem: Write a program to check if one string is a rotation of another (e.g., “waterbottle” is a rotation of “erbottlewat”).

Exercise Purpose: This exercise teaches Algorithmic Cleverness. While you could try to rotate the string manually in a loop, there is a “cheat code” logic that involves string concatenation, which is much more efficient.

Given Input: s1 = "waterbottle" s2 = "erbottlewat"

Expected Output: Is Rotation: True

Solution
def is_rotation(s1, s2):
    # Rotations must be the same length
    if len(s1) != len(s2):
        return False
    
    # Double the first string
    combined = s1 + s1
    
    # Check if s2 is inside the doubled version
    return s2 in combined

s1 = "waterbottle"
s2 = "erbottlewat"
print(f"Is '{s2}' a rotation of '{s1}'? {is_rotation(s1, s2)}")Code language: Python (python)

Explanation to Solution:

  • The Doubling Trick: waterbottlewaterbottle contains “erbottlewat” starting at the 3rd index. This trick covers all circular shifts.
  • Length Guard: We check len(s1) != len(s2) immediately. If they aren’t the same length, they can’t possibly be rotations, saving us unnecessary computation.
  • in operator: Python’s substring search is highly optimized, making this check very fast.

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

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

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

All Coding Exercises:

C Exercises
C++ Exercises
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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Ahmed Ibrahim says

    January 3, 2026 at 8:17 am

    First of all, thank you forever for this amazing website.

    Exercise 6: Create a mixed String using the following rules
    more pythonic way to solve this after 6 month digging into your website is:

    s1 = “Abc”
    s2 = “Xyz”

    s3 = list(zip(s1, s2[::-1]))
    joined = ”.join(a+b for a, b in s3)

    print(joined)

    Reply
  2. Vaidik 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
  3. Vaidik 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
  4. harry 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
  5. harry 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
  6. harry 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
  7. harry 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
    • Rieri says

      July 26, 2025 at 9:58 pm

      I think u are right

      Reply
  8. Stella 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
  9. Stella 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
  10. hamta 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
  11. Okbazghi says

    January 28, 2025 at 5:43 pm

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

    Reply
  12. karthik 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
  13. fasulu 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
    • Lokesh 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
      • Lokesh 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
      • Bogdan 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
  14. bigapple 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
    • dlinhares 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
  15. Walker 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
  16. panos 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
  17. panos 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
  18. panos 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
  19. panos 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
    • fasulu says

      January 21, 2024 at 6:04 pm

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

      Reply
  20. Irina 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
  21. m.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
  22. Millie 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
  23. ऋषित रघुवंशी 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
  24. ऋषित रघुवंशी 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
    • ऋषित रघुवंशी 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
  25. Viswanath 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
  26. hosein says

    August 23, 2023 at 3:30 am

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

    str1 = “Jemes”

    print(str1)

    res = str1[:: 2]

    print(“new string:”, res)

    Reply
    • Mohammad 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
  27. Ritabrata 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
  28. Ritabrata 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
  29. Habibur 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
  30. Leigh 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
  31. Anurag 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
  32. Anurag says

    March 22, 2023 at 7:10 pm

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

    Reply
  33. Mahesh 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
  34. Mahesh 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
    • mohammad basheer says

      August 18, 2023 at 8:41 pm

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

      Reply
  35. 0xAH says

    March 2, 2023 at 7:30 pm

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

    Reply
  36. 0xAH says

    March 2, 2023 at 7:27 pm

    # 1A

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

    Reply
  37. kalai 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
  38. Nermen says

    October 17, 2022 at 5:00 pm

    Question 7 :

    s1 = "Yn"
    s2 = "PYnative"

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

    Reply
    • Abhishek 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
  39. vini1955 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
  40. Shubham Yadav says

    October 8, 2022 at 9:27 pm

    Solution for 1A.

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

      January 28, 2023 at 5:13 pm

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

      Reply
  41. lily 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
    • VijayKumar 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
    • DJ 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
  42. Ali 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
    • malleswari 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
  43. Amir 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
    • chethan says

      October 4, 2022 at 4:33 pm

      None will come

      Reply
  44. Chinuogu 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
    • Chinuogu 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
  45. sruthy 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
  46. luke 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
  47. Prakash 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
  48. Prakash 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
  49. Swati 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
    • Sasidhar 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
    • lily 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
    • lily 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
    • Mahendra says

      May 28, 2025 at 6:39 pm

      Very good champ

      Reply
  50. kalyan 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
    • ram 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
  51. kalyan 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
  52. SinaJ 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
    • lily 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
      • lily 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
  53. Alvin 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
    • Alvin says

      May 5, 2022 at 2:00 pm

      i forgot to add s1.remove(None) though

      Reply
  54. Arnav 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
  55. Arnav 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
    • bro says

      April 27, 2022 at 3:56 am

      Can you pleas explain to me this code

      Reply
    • VijayKumar 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
  56. Rohit 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
  57. Rishikesh 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
  58. Vyom 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
    • Rishikesh 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
      • Ulvy 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
  59. Olasunkanmi 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
  60. Olaniyi 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
  61. Haarini 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
  62. Giorgos 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
  63. Prakash 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
    • prakash 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
      • Preetam 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
    • Gokul 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
  64. Inbar 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
  65. Danilo 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
  66. Danilo says

    November 18, 2021 at 1:41 pm

    Exercice 1A

    str1 = "James"
    print("String is:", str1)
    print("New string is: ", str[0::2])
    Reply
  67. Prem 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
  68. sama71 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
  69. Baraa 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
    • Olasunkanmi 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
  70. Mazhar 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
  71. amani 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
  72. P. 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
  73. P. 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
  74. P. 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
    • ashokkumar says

      September 6, 2023 at 9:55 pm

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

      Reply
  75. P. 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
  76. Chowdary 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
  77. P. 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
  78. P.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
  79. Raja 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
  80. Raja 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
    • Rishikesh 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
  81. Raja 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
  82. Subin jerin says

    July 20, 2021 at 11:03 pm

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

    Reply
    • Raja 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
  83. Meghna 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
  84. Karyse 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
    • Narendra 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
      • Danilo 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
  85. Meghna 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
  86. Soe 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
    • Tushar says

      April 24, 2022 at 5:09 pm

      Thanks awesome way brilliant thinking!!

      Reply
  87. Renegade 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
  88. Attiya 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
  89. Sat 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
  90. satheesh 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
  91. HT 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
  92. HT says

    January 29, 2021 at 2:36 am

    another solution to question 16

    
    import re
    str2 = re.sub(r"[^\d]", "", str1)
    print(str2)
    Reply
  93. Farish 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
  94. HT 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
    • Rishikesh 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
  95. Khanyi 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
  96. Rajkumar 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
    • Rishikesh 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
  97. Rajkumar 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
  98. Adham 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
  99. Adham 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
  100. Adham 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
  101. Adham 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
  102. sarika 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
  103. Amrita 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
    • AndyLeeParker says

      June 26, 2021 at 7:56 am

      Beautiful!

      Reply
  104. Rajkumar 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
  105. Rajkumar says

    December 24, 2020 at 4:17 pm

    Question 2

    s1 = "Ault"
    s2 = "Kelly"
    
    s3 = s1[:2]+s2[:]+s1[2:]
    print(s3)
    Reply
  106. Darrell 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
  107. ShwethaNagaraj 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
  108. Nik 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
  109. hemlata 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
    • neha says

      November 26, 2020 at 9:34 am

      where is ques

      Reply
    • Danilo 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
  110. Aishwary 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
  111. Aishwary 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
  112. Aishwary 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
  113. Abdu 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
  114. ur_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
  115. NerdAlert 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
    • Anita 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
  116. DMS 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
  117. DMS 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
    • apurv says

      September 7, 2020 at 7:39 pm

      thanks a lot

      Reply
  118. DMS 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
  119. DMS 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
  120. Akshata 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
  121. Galbatrollix 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
  122. Galbatrollix 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
  123. Bhavya 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
    • bhavya 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
  124. HOKAISEIG 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
    • Vishal 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
  125. Galbatrollix 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
    • Galbatrollix 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
      • Galbatrollix 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
  126. Dalvir 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
    • Dalvir says

      July 29, 2020 at 6:15 pm

      Above solution is for Q8

      Reply
  127. Mark 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
    • Vishal says

      July 28, 2020 at 11:49 am

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

      Reply
  128. shiva 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
  129. Mike 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
    • Vishal says

      July 10, 2020 at 11:27 am

      Yes, it was mistakenly written I have removed the condition

      Reply
  130. Aswathi 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
  131. Angshumaan 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
  132. SH 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
  133. JeromeLille 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
    • Danilo 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
  134. JeromeLille 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
  135. JeromeLille 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
  136. JeromeLille 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
  137. swagat 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
  138. Faizan Ahmed says

    May 27, 2020 at 9:36 am

    Really Helpful thanks a lot

    Reply
  139. SHINU 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
  140. SHINU 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
  141. Nitish Tomar says

    May 4, 2020 at 11:13 am

    you should have used __contains__() function also

    Reply
  142. Nikhil 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
  143. Nikhil 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
  144. Nikhil 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
  145. Nikhil 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
  146. Nikhil 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
  147. Nikhil 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
  148. Nikhil 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
    • Alec 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
      • Durga Sravanthi says

        October 27, 2020 at 12:32 pm

        middle_char = s1[(len(s1) / 2)] + s2[len(s2) /2]
        Reply
  149. Nikhil 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
  150. Nikhil 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
    • Yogi says

      April 25, 2022 at 12:11 pm

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

      Reply
  151. Prakash 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
    • Vishal 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
  152. AbduLLAH 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
    • Vishal 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
      • Prakash 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
  153. somnath 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
  154. Seetharam 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
  155. El 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
  156. Zlatko 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
  157. Waqar 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
  158. Uday 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
  159. Barry 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
  160. Barry 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
  161. Vitaliy says

    June 20, 2019 at 8:12 pm

    Q10

    str1 = input("Input word : ")
     print({c : str1.count(c) for c in str1})
    
    Reply
  162. Tarun 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
    • Vignesh 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
    • sonali says

      July 31, 2020 at 2:34 pm

      bro please check your code, it has errors

      Reply
    • Abdullah says

      January 3, 2023 at 1:35 pm

      🤔🤔

      Reply
  163. Bill 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
  164. Bill 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
  165. Bill 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
  166. Bill 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
    • Tarun 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
  167. Bill 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
    • Vishal 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
  168. Bill 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
    • Barry 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
    • Nvm says

      October 31, 2023 at 7:07 pm

      It does not match the expected output.

      Reply
  169. Bill 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 Exercises for Beginners
  • Loop Exercises
  • Intermediate Python Exercises
  • Input and Output Exercises
  • Functions Exercises
  • String Exercises
  • List Exercises
  • Dictionary Exercises
  • Set Exercises
  • Tuple Exercises
  • Data Structure Exercises
  • Comprehensions Exercises
  • Collections Module Exercises
  • Date and Time Exercises
  • OOP Exercises
  • Exception Handling Exercises
  • Math and Statistics Exercises
  • File Handling Exercises
  • OS and Sys Module Exercises
  • Regex Exercises
  • Lambda & Functional Programming Exercises
  • Iterators & Generators Exercises
  • Itertools & Functools Exercises
  • Random Data Generation Exercises
  • NumPy Exercises
  • Pandas Exercises
  • Matplotlib Exercises
  • Python Database Exercises
  • Python JSON Exercises

 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.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

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–2026 pynative.com

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有