Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this ternary operator? [duplicate]

Tags:

python

for i in str1:
    (newstr += chr(ord(i)+2)) if i.isalpha() else (newstr += i)

It seems to be grieving about the += operator. I know both my variables are strings though, so I don't understand why it would not just concatenate them

like image 557
chopper draw lion4 Avatar asked Nov 24 '25 15:11

chopper draw lion4


1 Answers

Try the following:

for i in str1:
    newstr += (chr(ord(i)+2) if i.isalpha() else i)

Edit:

From python documentation:

conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr

And as pointed by @flornquake, the assignment var += value is a statement, not an expression.

like image 138
Rubens Avatar answered Nov 27 '25 04:11

Rubens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!