如何在Python中使用多个{}干净地格式化字符串,还需要忽略?

问题描述 投票:0回答:1

在Python中为Splunk访问设置搜索查询。然而,在我跑步期间,我遇到了IndexError: tuple index out of range。我在我的代码中找到了多个{}并尝试使用.format最早应用变量,最新导致所述错误。

我已经尝试切换到.format_map,但除非我做错了,否则会导致更多错误。 (可能是)

我无法更改代码中的字符串。所以我试图找到将时间变量附加到字符串以供使用的方法。

以下是变量调用:

import _datetime_param
_earliest = _datetime_param.earliest()
_latest = _datetime_param.latest()

格式化工作:

def eop():
    search_query = (
        'index="eop" sourcetype="eop:trace" Status="Quarantined" earliest={} latest={} | '
        'convert timeformat="%Y-%m-%d %I:%M:%S" ctime(_time) as Date | '
        'table Date src_ip src_user subject recipient | sort Date'
    ).format(_earliest, _latest)
    search_query.strip()
    if not (search_query.startswith('search') or search_query.startswith('|')):
        search_query = 'search ' + search_query
    return search_query

运行格式为错误:

def okta():
    search_query = (
        'index="okta" user!="CityADSync" action="failure" earliest={} latest={} | '
        'convert timeformat="%Y-%m-%d %I:%M:%S" ctime(_time) AS Date | dedup actors{}.ipAddress | '
        'rename actors{}.ipAddress AS IPAddress | rename actors{}.id AS Device | rename targets{}.id AS TargetID | '
        'rename targets{}.displayName AS TargetName| rename targets{}.login AS TargetLogin | '
        'table Date Device IPAddress TargetID TargetName TargetLogin | sort Date'
    ).format(_earliest, _latest)
    search_query.strip()
    if not (search_query.startswith('search') or search_query.startswith('|')):
        search_query = 'search ' + search_query
    return search_query

def okata():中,我无法将search_query更改为在Splunk中以此方式运行。所以我正在寻找一种方法来干净地处理两种方式而不会遇到错误。直截了当是否有一种方法在Python中忽略{}你不想使用?如果它是.format_map,有没有一个干净的方法这样做,我失踪了?

提前致谢!

python format splunk
1个回答
0
投票

我可以使用f String

你的字符串保持为:

string = f' a text {var} other text {other_var}'

© www.soinside.com 2019 - 2024. All rights reserved.