等效于= +的字符串,但现有字符串被追加,而不是在新字符串之前 [英] String equivalent of =+ but existing string as appended rather than prepended to new string

查看:122
本文介绍了等效于= +的字符串,但现有字符串被追加,而不是在新字符串之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PyCharm(版本4.0.3)并收到样式警告可以在以下代码的第二行*上用增强分配替换赋值:

I'm using PyCharm (version 4.0.3) and getting a style warning Assignment can be replaced with augmented assignment on the second line of the following code*:

abc = 'and cheese'
abc = 'ham' + abc

*-我的代码不是真正的这段代码,但是会产生相同的错误.我正在以编程方式生成两个字符串,我必须/想在第二行(英语语法的第一部分)之前生成第一行(英语语法的第二部分).

* - My code is not really this code but it generates the same error. I am programmatically generating two strings and I have to / would like to generate the first line (second part of the English syntax) before the second line (the first part of the English syntax).

但是我不知道什么是扩充作业可以做到这一点.如果代码是这样的(所需的最终字符串的第一部分可以按照执行顺序首先生成)

But I don't know what augmented assignment could do this. If the code were like this (where the first part of the desired final string could be generated first in execution order)

abc = 'ham'
abc = abc + 'and cheese'

然后,我相信使用+ =运算符可以轻松解决问题:

then I believe the problem is trivially resolved with the += operator:

abc = 'ham'
abc += 'and cheese'

但是在我的问题(和奶酪"部分在火腿"之前声明)的背景下,有没有办法满足这个警告?

But in the context of my problem (where the 'and cheese' part is declared before 'ham'), is there a way to satisfy this warning?

推荐答案

有多种方法可以为猫皮(或约束 cat 设置字符串).

There are more than one way to skin a cat (or to concatenate strings).

您可以使用str.join进行串联,但对于小列表而言,效率可能稍低:

You can concatenate using str.join but it may be marginally less efficient for small lists:

abc = " ".join((abc, 'and cheese'))

或使用格式:

abc = "{} {}".format(abc, 'and cheese')

但是,实际上,消除警告的正确方法是为IDE提交错误报告,因为看起来您的代码没有问题(注释中的某人已指出该代码在上一版本中不可复制) ).

But really, the correct way to silence the warning is to submit a bug report for the IDE, because it looks like there is nothing wrong with your code (someone in the comments already pointed out it is not reproducible on the last version).

这篇关于等效于= +的字符串,但现有字符串被追加,而不是在新字符串之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆