Computer Science
Write a method in python to display the elements of list thrice if it is a number and display the element terminated with '#' if it is not number.
For example, if the content of list is as follows :
List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA']
The output should be
414141
DROND#
GIRIRAJ#
131313
ZAR#
Python List Manipulation
5 Likes
Answer
def display(my_list):
for item in my_list:
if item.isdigit():
print(item * 3)
else:
print(item + '#')
display(my_list = eval(input("Enter the list :")))
Output
Enter the elements of the list separated by spaces:41 DROND GIRIRAJ 13 ZARA
414141
DROND#
GIRIRAJ#
131313
ZARA#
Explanation
- The code prompts the user to enter the elements of the list separated by spaces and stores the input as a single string in the variable
my_list
. - Then splits the input string my_list into individual elements and stores them in a new list called
new_list
. - Then for loop iterates over each element in the new_list.
- The
isdigit()
method is used to check if all characters in the string are digits. If it's true (i.e., if the element consists only of digits), then it prints the element concatenated with itself three times. Otherwise, if the element contains non-digit characters, it prints the element concatenated with the character '#'.
Answered By
1 Like
Related Questions
What will be the output of the following code snippet ?
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"} id1 = id(rec) del rec rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"} id2 = id(rec) print(id1 == id2)
- True
- False
- 1
- Exception
Write the output of the code given below :
my_dict = {"name" : "Aman", "age" : 26} my_dict['age'] = 27 my_dict['address'] = "Delhi" print(my_dict.items())
Name the function/method required to
(i) check if a string contains only uppercase letters.
(ii) gives the total length of the list.
What will be the output of the following code snippet ?
my_dict = {} my_dict[(1,2,4)] = 8 my_dict[(4,2,1)] = 10 my_dict[(1,2)] = 12 sum = 0 for k in my_dict: sum += my_dict[k] print(sum) print(my_dict)