简体   繁体   中英

Trouble converting integer to string in a list using Python

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:

  1. First of all I recommend using different names for the parameters defined in your function and the actual object you later feed in to the function. This will help avoid confusion for you (as a beginner), for us (trying to help debug the code), and in the future any people you work or code with.
  2. You stated your goal was to convert some integer elements to strings, however the methods used in your function will just assess each element and then based on the condition (in your if statement) add an additional string ('Fizz' or 'buzz') to the list or add an additional copy of the element (e) to the list.
  3. The error you are getting is due to the for loop reaching those additional string elements of the list, which it doesn't know how to process: if ('Fizz' % 3) ==0:
    The modulus operator can only handle integers; not strings.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM