我有一个字符串,我想将一个变量放在其中的多个位置:
query_1 ='SELECT distinct ?a\
WHERE { ?a rno:end_at ?b.\
?b rdf:type rno:Node; rno:is_extent_of ?x.\
?x rno:builds %s. %s a rno:Roundabout.\
FILTER(NOT EXISTS {?a rno:builds %s})} ORDER BY ?a'%(ref_RaURI, ref_RaURI,ref_RaURI)
print query_1
上面的替换有效,但我不想重复变量 ref_RaURI,所以我尝试了以下操作:
query_1 ='SELECT distinct ?a\
WHERE { ?a rno:end_at ?b.\
?b rdf:type rno:Node; rno:is_extent_of ?x.\
?x rno:builds {0}. {0} a rno:Roundabout.\
FILTER(NOT EXISTS {?a rno:builds {0}})} ORDER BY ?a'.format(ref_RaURI)
print query_1
这个正在返回:
FILTER(NOT EXISTS {?a rno:builds {0}})} ORDER BY ?a'.format(ref_RaURI)
KeyError: ' ?a rno'
使用字典:
query_1 ="SELECT distinct ?a\
WHERE { ?a rno:end_at ?b.\
?b rdf:type rno:Node; rno:is_extent_of ?x.\
?x rno:builds %(s). %(s) a rno:Roundabout.\
FILTER(NOT EXISTS {?a rno:builds %(s)})} ORDER BY ?a"%{'s':ref_RaURI}
print query_1
返回:
FILTER(NOT EXISTS {?a rno:builds %(s)})} ORDER BY ?a"%{'s':ref_RaURI}
ValueError: unsupported format character ' ' (0x20) at index 140
有什么办法可以让它发挥作用吗?
最佳答案
此外,当使用 %
符号进行字符串格式化时,您可以指定如下关键字参数(直接取自您的示例):
pattern ='SELECT distinct ?a\
WHERE { ?a rno:end_at ?b.\
?b rdf:type rno:Node; rno:is_extent_of ?x.\
?x rno:builds %(p1)s. %(p1)s a rno:Roundabout.\
FILTER(NOT EXISTS {?a rno:builds %(p1)s})} ORDER BY ?a'
params = dict(p1=ref_RaURI)
# equal to
# params = {'p1': ref_RaURI}
query_1 = pattern % params
字符串格式化运算符%
有多个选项。最常见的情况是将其用作 %s
。 W它只是插入变量的字符串表示形式。还有其他选项,例如 %c
- 字符、%d
- 数字等。
除此之外,它还支持关键字参数。这意味着,当您传递字典作为格式化源时,您可以为 %
运算符指定给定字典的键,如下所示:
d = {'one': 'first param', 'two': 'second param'}
print 'Few options here: %(one)s and %(two)s' % d
%(one)s
表示:通过键 one
从字典中获取值,并将其字符串表示形式 (%s
)。相同的规则适用于所有参数。如果你只想使用 %(one)
,这是行不通的,因为你需要提供类型,即应该打印哪个值,其中 %s
代表字符串.
关于python - 在字符串中的多个位置替换变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31788448/