Sami
Sami

Reputation: 486

String formatting with concatenation

I am trying to concatenate the string and number with string formatting, but I am getting an error

"TypeError: not all arguments converted during string formatting"

This is my code

i = 0
while (i<= 10):
  print("insert into Member" + "(Mem_ID)")
  print("values" + "(" + "Mem%d" +  ")" %(i))
i = i+1

Upvotes: 1

Views: 82

Answers (2)

Mike - SMT
Mike - SMT

Reputation: 15226

The problem is how you are using %

The %d that is being replaced should have %(var) next to the quote.

i = 0
while (i<= 10):
    print("insert into Member " + "(Mem_ID)")
    print("values " + "(" + "Mem%d"%(i) +  ")" )
    i += 1

keep in mind you should be using .format() as the current method.

i = 0
while (i<= 10):
    print("insert into Member " + "(Mem_ID)")
    print("values " + "(" + "Mem{}".format(i) +  ")" )
    i += 1

Also to be clear some of your quotes are not needed. You can also use this.

i = 0
while (i<= 10):
    print("insert into Member (Mem_ID)")
    print("values (Mem{})".format(i))
    i += 1

Upvotes: 4

developer_hatch
developer_hatch

Reputation: 16224

You can do this much more simplier if you convert the int into a string like this:

i = 0
while (i<= 10):
    print("insert into Member " + "(Mem_ID)")
    print("values " + "(" + "Mem" + str(i) + ")")
    i = i+1

Upvotes: 2

Related Questions