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
  • 506,650
  • 124
  • 909
  • 1,183

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,060
  • 19
  • 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)
Suren
  • 5,775
  • 3
  • 26
  • 39
holdenweb
  • 27,899
  • 7
  • 50
  • 73
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,577
  • 4
  • 42
  • 65
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
  • 21,617
  • 13
  • 80
  • 125
  • 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