I'm trying to convert certain integers in a list to a string, but I keep getting an error that I think has to do with converting the integer into a string. I've tried str(), but it doesn't seem to solve the problem. I think I may be doing something else wrong. My code is as follows:
intList = [1,2,3,4,5]
def fizzbuzz(intList):
for e in intList:
if (e % 3) ==0:
e='Fizz'.join(str(e) for e in intList)
if (e % 5) ==0:
e='Buzz'.join(str(e) for e in intList)
print fizzbuzz (intList)
I get this error:
TypeError: not all arguments converted during string formatting
I've also tried changing it a bit but keep getting the same string formatting error:
def fizzbuzz(intList):
for e in intList:
if (e % 3) ==0:
intList.append(str('Fizz'))
elif (e % 5) ==0:
intList.append(str('Buzz'))
else:
intList.append(e)
print fizzbuzz (intList)
I can't figure out another way to fix the string error. I've searched around and think it may be a problem with %?
There are a few things wrong here:
if ('Fizz' % 3) ==0:
Hopefuly this will provide you with enough insight to fix your code. If not then we are here!
The problem is because of this section of code:
if (e % 3) ==0:
e='Fizz'.join(str(e) for e in intList)
if (e % 5) ==0:
e='Buzz'.join(str(e) for e in intList)
if e
is evenly divisible by 3, then e
is changed to a string. The next if
statement then tries to %
e
(the string) by 5. In Python, %
with a string does something totally different than it does with a number (it substitutes values into it) and the error message is related to that.
The solution is to use a different variable name for the string that contains Fizz
or Buzz
.
There are other problems with your code; ask again when you run into them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.