[英]String equivalent of +=
字符串的+ =是否等效?
即:
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...')
如果使用與數字相同的規則,則應返回a string and a second string
。 是否有可能做到這一點? 因為這樣做只會返回TypeError: unsupported operand type(s) for +=: 'int' and 'str'
,即使y
是開頭的字符串,而不是int
。
如果這樣做:將一個字符串連接到一個字符串:
x = 'a string'
x += '6'
print x
如果執行此操作:將int連接到字符串,則出現錯誤:
x = 'a string'
x += 6
print x
錯誤:
TypeError: cannot concatenate 'str' and 'int' objects
在執行“ +”操作之前,必須確保變量類型; 根據變量類型,python可以添加或連接
那將是s1 += s2
:
>>> s1 = "a string"
>>> s1 += " and a second string"
>>> s1
'a string and a second string'
>>>
與Perl不同,Python大多拒絕執行隱式轉換(數字類型是主要例外)。 要將整數i
的字符串表示形式連接到字符串s
,您必須編寫
s += str(i)
以下代碼對我適用於Python 2.7.4和Python 3.0:
a='aaa'
a+='bbb'
print(a)
aaabbb
我不知道,但是也許您正在尋找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
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...')
這很簡單。 首先將X
定義為integer
,然后在while
循環中將其遞增。
在每次迭代的開始,您都定義y = x
,這實際上告訴python將y
設置為整數。
然后根據獲得的x modulus <nr>
,將一個string
添加到稱為y
的整數中(是,它也是一個整數)。這會導致錯誤,因為這是一個非法操作,因為INT
和一個WORD
可以工作,它們只是不同WORD
,因此您需要在將它們合並到同一變量之前對其進行處理。
如何調試自己的代碼:嘗試執行print(type(x), type(y))
,您會得到兩個變量的區別。可能會幫助您解決這個問題。
解是y = str(x)
。
因為你重新定義y
您的每一次迭代while
循環。
y = x
<-使Y
成為整數,因為x
就是這個意思:)
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...')
另一個個人觀察結果是,如果x % 3 == 0
,則替換y = ...
,但是在所有其他if情況下,您都附加到y
,這是為什么呢? 我離開它只是你給我們的代碼的方式,但無論是做elif
在休息或why not concade on all
如果's
我設法使用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...')
請告訴我這個特別糟糕的代碼(我有寫習慣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.