有没有办法阻止python连接空格分隔的字符串? [英] is there any way to stop python to concatanate space delimited strings?

查看:34
本文介绍了有没有办法阻止python连接空格分隔的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我们在基于代码的代码中发现了一些错误,因为开发人员忘记在字符串列表中间添加逗号,而 python 只是连接了字符串.往下看:

Recently we found a couple of bugs in our code based because a developer forgot to add a comma in the middle of a list of strings and python just concatenated the strings. look below:

预期的列表是:["abc", "def"]

The intended list was: ["abc", "def"]

开发者写道:[ABC""定义"]

Developer wrote: ["abc" "def"]

我们得到:["abcdef"]

and we got: ["abcdef"]

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

now I am concerned over similar mistakes in other part of the code, is this functionality a core part of python? is it possible to disable it?

推荐答案

是的,这是一个 python的核心部分:

多个相邻的字符串文字(由空格分隔),可能允许使用不同的引用约定,它们的含义是与它们的串联相同.因此, "hello" 'world' 是等价的helloworld".

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 本身.

I don't think there is a way to disable it, short of hacking Python itself.

但是,您可以使用下面的脚本来标记化您的代码和当它找到多个相邻的字符串时发出警告:

However, you could use the script below to tokenize your code and warn you when it finds multiple adjacent strings:

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"]

这篇关于有没有办法阻止python连接空格分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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