有没有办法阻止python合并空格分隔的字符串?

2024-04-26 22:06:24 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,我们在基于代码的代码中发现了几个bug,因为开发人员忘记在字符串列表的中间添加逗号,而python只是将字符串串联起来。 请看下面:

预定名单是: [“abc”,“def”]

开发商写道: [“abc” “定义”]

我们得到:[“abcdef”]

现在我担心代码的其他部分会出现类似的错误,这个功能是python的核心部分吗?是否可以禁用它?你知道吗


Tags: 字符串代码功能核心列表定义开发人员def
1条回答
网友
1楼 · 发布于 2024-04-26 22:06:24

是的,这是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"]

相关问题 更多 >