0

Is there an equivalent of += for a string?

ie:

x = 1
while x <= 100:
    y = x
    if x % 3 == 0:
        y = 'Fizz'
    if x % 5 == 0:
        y += 'Buzz'
    if x % 7 == 0:
        y += 'Foo'
    if x % 11 == 0:
        y += 'Bar'
    print y
    x += 1
raw_input('Press enter to exit...')

This should return a string and a second string if the same rules as with numbers applied. Is it possible to do this? Because just doing that returns TypeError: unsupported operand type(s) for +=: 'int' and 'str', even though y is a string to begin with, not an int.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 4
    Hmm, I don't see a `y` in your snippet... – lc. Mar 07 '14 at 07:50
  • Should work fine, check your assumptions. – Brave Sir Robin Mar 07 '14 at 07:50
  • The code snippet you show is okay. Something else must be wrong. – Some programmer dude Mar 07 '14 at 07:50
  • It works fine for me. Are you sure that `y` is not an integer? – Joel Cornett Mar 07 '14 at 07:50
  • 2
    You can not (obviously) join a `string` with a `integer` by doing `"some string" + 1`, but you can do `"some string" + str(1)` obviously. There's no other ways of doing it. – Torxed Mar 07 '14 at 07:52
  • possible duplicate of [Python String and Integer concatenation](http://stackoverflow.com/questions/2847386/python-string-and-integer-concatenation) – devnull Mar 07 '14 at 07:52
  • @lc thats because the error was from another piece of code, a fizzbuzz i was making. ill edit the op with all my code –  Mar 07 '14 at 07:53
  • Ahh, i see what i did. If the first if is skipped, then the second assumes that the first was true, thats where the error is. –  Mar 07 '14 at 08:04
  • In fact a single change of `y = x` to `y = str(x)` would avoid the error. You should use `+=` for `'Fizz'` as well! – holdenweb Jun 24 '19 at 15:59
  • "Even though `y` is a string to begin with, not an `int`" **This is not the case** (unless `x` is divisible by `3`). Voting to close as a typo. [Please try](https://meta.stackoverflow.com/questions/261592) to [track down such problems](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) before posting. – Karl Knechtel Jul 27 '22 at 02:48

6 Answers6

3

If you do this: You are concatenating a string to string:

x = 'a string'
x += '6'
print x

If you do this: You concatenate int to string so you get error:

x = 'a string'
x += 6
print x

error:

TypeError: cannot concatenate 'str' and 'int' objects

You have to make sure variable type before doing '+' operation; based on variable type, python can add or concatenate

venpa
  • 4,268
  • 21
  • 23
1

That would be s1 += s2:

>>> s1 = "a string"
>>> s1 += " and a second string"
>>> s1
'a string and a second string'
>>>

Unlike Perl, Python mostly refuses to perform implicit conversions (the numeric types being the principal exception). To concatenate the string representation of an integer i to a string s, you would have to write

s += str(i)
kangaroo_cliff
  • 6,067
  • 3
  • 29
  • 42
holdenweb
  • 33,305
  • 7
  • 57
  • 77
1

The following code works for me for Python 2.7.4 and Python 3.0:

a='aaa'
a+='bbb'
print(a)
aaabbb
vicsana1
  • 359
  • 1
  • 4
0

I don't know, but maybe you are looking for operator

operator.iadd(a, b)¶
operator.__iadd__(a, b)
a = iadd(a, b) is equivalent to a += b.

http://docs.python.org/2/library/operator.html

x = 'a string'
x += ' and a second string'
print x

operator.iadd(x, ' and a third string')

print x

How can I concatenate a string and a number in Python?

Community
  • 1
  • 1
blfuentes
  • 2,731
  • 5
  • 44
  • 72
0
x = 1
while x <= 100:
    y = str(x)
    if x % 3 == 0:
        y = 'Fizz'
    if x % 5 == 0:
        y += 'Buzz'
    if x % 7 == 0:
        y += 'Foo'
    if x % 11 == 0:
        y += 'Bar'
    print y
    x += 1
raw_input('Press enter to exit...')

It's quite simple. You start off by defining X as an integer, then you increese it in a while loop.
At the very beginning of each iteration you define y = x which essentially tells python to set y into an integer.

Then depending on what x modulus <nr> you got, you add a string to the integer called y (yes, it is an integer as well).. This leads to an error because it's an illegal operation because of the way a INT and a WORD works, they're just different so you need to treat one of them prior to merging them into the same variable.

How to debug your own code: Try doing print(type(x), type(y)) and you get the differences of the two variables.. Might help you wrap your head around this.

The solution is y = str(x).

So, no.. Y is NOT a string to begin with

Because you redefine y each iteration of your while loop.
y = x <-- Makes Y a int, because that's what x is :)

Also, try using .format()

x = 1
while x <= 100:
    y = x
    if x % 3 == 0:
        y = '{0}Fizz'.format(x)
    if x % 5 == 0:
        y += '{0}Buzz'.format(x)
    if x % 7 == 0:
        y += '{0}Foo'.format(x)
    if x % 11 == 0:
        y += '{0}Bar'.format(x)
    print y
    x += 1
raw_input('Press enter to exit...')

Another personal observation is that if x % 3 == 0 you replace y = ..., but in all other if-cases you append to y, why is this? I left it just the way you gave us the code but either do elif on the rest or why not concade on allif's

Torxed
  • 22,866
  • 14
  • 82
  • 131
  • ahh, yes. So is this better than the solution I came up with? (look down a few answers) –  Mar 07 '14 at 08:13
  • @mm865 Considering i changed 1 line of code, you doubled the code.. I'd say mine makes more sense? Altho all answers are good answers i personally think you should not mess with the code to much in order to fix an issue unless you gain more functionality out of it. So in this particular case, i think my code will be understood quicker and be more efficient considering i only added 5 characters of code on 1 line in order to achieve the same outcome? :) **Also**, in 100% of the cases, you will replace `Y` with for instance `Foo`, his expected result is ` Foo`? – Torxed Mar 07 '14 at 08:14
0

I managed to fix it using isinstance()

x = 1
while x <= 100:
    y = x
    if x % 3 == 0:
        y = 'Fizz'
    if x % 5 == 0:
        if isinstance(y, str):
            y += 'Buzz'
        else:
            y = 'Buzz'
    if x % 7 == 0:
        if isinstance(y, str):
            y += 'Foo'
        else:
            y = 'Foo'
    if x % 11 == 0:
        if isinstance(y, str):
            y += 'Bar'
        else:
           y = 'Bar'
    print y
    x += 1
raw_input('Press enter to exit...')

Please tell me if this particularly bad code (which I have a habit of writing).

  • @Torxed won't that mean that if the first `if` is skipped, `y` will be `xBuzz`? –  Mar 07 '14 at 08:16
  • @Torxed yep, tried that out just returns e.g `xFooBar` (where x is the number) instead for `FooBar` –  Mar 07 '14 at 08:19