【问题标题】:Trouble using tuple along with other strings when passing them to .format in Python within a string在字符串中将元组与其他字符串一起传递给 Python 中的 .format 时出现问题
【发布时间】:2018-12-26 13:18:13
【问题描述】:

我有以下 TOML:

[gps]
measurement = "gps"
tags = ["lat", "lon", "alt"]
limit = 10

在 Python 中翻译成以下字典:

{
  "gps": {
       "measurement": "gps",
       "tags": [ "lat", "lon", "alt"],
       "limit": 10
}

我有一个类,我希望创建一个成员函数read_gps,如下所示:

  1. 从上面的字典中获取**kwargs
  2. 目前,只需打印以下字符串: select "lat", "lon", "alt", from "gps" limit 10

代码

class dbClass:
    def __init__(self, db=None, **kwargs):
        self.kwargs = kwargs # this kwargs is different from the above kwargs
        # do some initialization stuff here

     def read_gps(self, **kwargs):
        # pass the above mentioned dict here
        # instance_dbClass.read_gps(gps_dict)

        _data = kwargs
        _tags = kwargs.get('tags')

        print('select "{}","{}","{}" from "{}" limit {}'.format(*_tags,
                          _data.get('measurement'), 
                          _data.get('limit'))
        )

但我收到以下错误:

SyntaxError: only named arguments may follow *expression

相反,如果我删除measurementlimit,它会正常工作。

实现此目的的 Python 方法是什么?我应该创建两个不同的字符串,然后最后将它们连接起来吗?

试用

query = """
        select "{}", "{}", "{}" from "{}" limit {}
        """.format(_tags[0], _tags[1], _tags[2], _data.get('measurement'),
                   _data.get('limit'))
print(query)

但是它有一种方法可以使用 * 解包 .format() 中的元组以及其他值

【问题讨论】:

  • 对我来说很好用。
  • 您是指* 吗?
  • 是的,你的 python 版本是什么? 3.6 ?
  • 我使用的是 3.4.3

标签: python python-3.x string


【解决方案1】:

您的代码将在 Python 3.5+ 版本中运行,遵循Pep 448。如果必须使用低于 3.5 的版本,可以使用命名参数:

print(select "{}","{}","{}" from "{measurement}" limit {limit}'.format(*_tags, measurement=measurement, limit=limit))

或者,首先将_tags 加入一个字符串:

print('select "{}" from "{}" limit {}'.format('","'.join(_tags), measurement, limit))

即使_tags 的长度发生变化,第二个选项也会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多