'count function in python list
Hello comrades, I want to take a character from the input and convert it to a list, and then show the number of repetitions of each index to the user, but it gives an error.
my code:
list = list(input("plase enter keyword"))
for item in list:
print(f"value({item})"+list.count(item))
my error
TypeError
Traceback (most recent call last)
c:\Users\emanull\Desktop\test py\main.py in <cell line: 3>()
2 list = list(input("plase enter keyword"))
4 for item in list:
----> 5 print(f"value({item})"+list.count(item))
TypeError: can only concatenate str (not "int") to str
Solution 1:[1]
list_ = list(input("plase enter keyword"))
for item in list_:
print(f"value({item}) {list_.count(item)}")
OR
list_ = list(input("plase enter keyword"))
for item in list_:
print(f"value({item})"+str(list_.count(item)))
Solution 2:[2]
Firstly overshadowing list
built-in is bad idea, secondly you need to convert number into str
if you want to concatenate it with other str
, after applying these changes
lst = list(input("plase enter keyword"))
for item in lst:
print(f"value({item})"+str(lst.count(item)))
but be warned that it will print more than once for repeated item
Solution 3:[3]
I think the reason for the error is that you are trying to concatenate a string and a integer which is not possible in python unlike javascript.So try to convert your integer to a string using str keyword and then concatenate.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Daweo |
Solution 3 | Arun |