最近我们在基于代码的代码中发现了几个错误,因为开发人员忘记在字符串列表的中间添加逗号,而 python 只是连接字符串。 看下面:
预期列表是: ["abc", "def"]
开发者写道: [“abc” “定义”]
我们得到:["abcdef"]
现在我担心代码的其他部分也有类似的错误,这个功能是python的核心部分吗?是否可以禁用它?
请您参考如下方法:
是的,这是一个core part of python :
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus,
"hello" 'world'is equivalent to"helloworld".
我认为没有办法禁用它,除非破解 Python 本身。
但是,您可以使用下面的脚本来 tokenize您的代码并在发现多个相邻字符串时警告您:
import tokenize
import token
import io
import collections
class Token(collections.namedtuple('Token', 'num val start end line')):
@property
def name(self):
return token.tok_name[self.num]
def check(codestr):
lastname = None
for tok in tokenize.generate_tokens(io.BytesIO(codestr).readline):
tok = Token(*tok)
if lastname == 'STRING' and lastname == tok.name:
print('ADJACENT STRINGS: {}'.format(tok.line.rstrip()))
else:
lastname = tok.name
codestr = '''
'hello'\
'world'
for z in ('foo' 'bar', 'baz'):
x = ["abc" "def"]
y = [1, 2, 3]
'''
check(codestr)
产量
ADJACENT STRINGS: 'hello''world'
ADJACENT STRINGS: for z in ('foo' 'bar', 'baz'):
ADJACENT STRINGS: x = ["abc" "def"]
