Exercise 1

 

Exercise: Display numbers divisible by 5 from a list

#Program:

num_list = [10, 20, 33, 46, 55]

print("Given list:", num_list)

print('Divisible by 5:')

for num in num_list:

    if num % 5 == 0:

        print(num)

 

Output:

Given list: [10, 20, 33, 46, 55]

Divisible by 5:

10

20

55

 

 

Exercise : Return the count of a given substring from a string

Write a program to find how many times substring “Rahul” appears in the given string.

Program:

str_x = "Rahul is good developer. Rahul is a writer"

# use count method of a str class

cnt = str_x.count("Rahul")

print(cnt)

 

Output:

2

 

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

#Program:

sample_str = "Hello123world@$$"

 

char_count = 0

digit_count = 0

symbol_count = 0

 

for char in sample_str:

    if char.isalpha():

        char_count += 1

    elif char.isdigit():

        digit_count += 1

    # if it is not letter or digit then it is special symbol

    else:

        symbol_count += 1

   

print("total counts of chars, Digits, and symbols \n")

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

 

Output:

total counts of chars, Digits, and symbols

Chars = 10 Digits = 3 Symbol = 3

 

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

Write a program to find all occurrences of “USA” in a given string ignoring the case.

Program:

str1 = "Welcome to INDIA. India awesome, isn't it?"

search_str = "india"

 

# convert string to lowercase

temp_str1 = str1.lower()

 

temp_str2 = search_str.lower()

 

# use count function

count = temp_str1.count(temp_str2)

print("The india count is:", count)

 

Output:

The india count is: 2

 

Comments