Python-字符串format方法指定参数
一、字符串的format方法有几种指定参数的方式:
(1)按照位置传参(默认方式),传入的参数与{}一一对应
(2)关键字传参,关键字(keyword)传递是根据每个参数的名字传递参数。关键字并不用遵守位置的对应关系。
(3)位置传参与关键字传参混合使用。
二、详细描述字符串的format方法如何格式化字符串:
第一种方法:
s1 = 'Today is {},the temperature is {} degrees.' print(s1.format('Saturday',24))
第二种方法:
s2 = 'Today is {day},the temperature is {degree} degrees.' print(s2.format(degree = 30,day = 'Saturday'))
第三种方法:
s4 = Today is {week},{1},the {0} temperature is {degree} degree.' print(s4.format('abds',1234,degree = 45,week = 'Sunday'))
拓展—如果是对象呢:
class Person: def __init__(self): self.age = 12 self.name - 'Bill' person = Person() s5 = "My name is {p.name},my age is {p.age}." print(s5.format(p = person))
问题:如果format的字符串中含有正则表达式时,比如str = """select regexp_replace('test20230301','[0-9]{8}|[0-9]{6}','') from ads_project_table_relation where ds = {0} """ 在使用format函数指定参数就会报错:IndexError: tuple index out of range 。
原因分析:正则表达式中匹配长度{8} 和 {6},在调用format方法时和需要传参的{0}冲突。
解决办法:将不是传参部分的{和},使用{{和}}进行替换。
即:str = """select regexp_replace('test20230301','[0-9]{{8}}|[0-9]{{6}}','') from ads_project_table_relation where ds = {0} """
如果你需要在Python的字符串中包含${}
而不是作为格式化占位符使用,你可以通过在${}
前面加上另一个${}
来实现转义。
比如:对于SQL语句:select * from table_name where ds = ${bizdate} ,我只想将表名作为参数传入。
sql = "select * from {0} where ds = ${bizdate}" print(sql.format("table_name"))
代码这样写,执行就会报错:KeyError: 'bizdate'
这种情况应该使用{}对于{}进行转义,代码如下:
sql = "select * from {0} where ds = ${{bizdate}}" print(sql.format("table_name"))
本文来自博客园,作者:业余砖家,转载请注明原文链接:https://www.cnblogs.com/yeyuzhuanjia/p/17359213.html