python 怎么在字符串中使用变量?

python 怎么在字符串中使用变量?
我有一条SQL语句,想把里面的年月日改成变量应该怎么写
select * from usb where time between to_date('2012-04-06 00:00:00','YYYY-MM-DD HH24:MI:SS') and to_date('2012-04-06 23:59:59','YYYY-MM-DD HH24:MI:SS')

1. 使用连接符: +

world = "World"
print "Hello " + world + " ! "

2. 使用占位符来内插

world = "World"
print "Hello %s !" % world

3. 使用函数

li = ['my','name','is','bob']
mystr = ' '.join(li)
print mystr

 上面的语句中字符串是作为参数传入的,可以直接用变量替换:

begin_date = '2012-04-06 00:00:00'
end_date = '2012-04-06 23:59:59'
select * from usb where time between to_date(begin_date,'YYYY-MM-DD HH24:MI:SS') and to_date(end_date,'YYYY-MM-DD HH24:MI:SS')

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-06
使用正则表达式,将里面的字符串提取出来。参考正则表达式模块(re module),取出匹配的串后,调用int(变量)转成你要的数据。

参考:
import re

s = """2012-04-06 23:59:59"""

reObj = re.compile(r"(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)")
matchObj = reObj.match(s)

year = int(matchObj.group(1))
month = int(matchObj.group(2))
day = int(matchObj.group(3))

print year,month,day
第2个回答  2012-04-12
"select * from usb where time between %s and %s" %('2012-04-06 00:00:00','2012-04-06 23:59:59')
第3个回答  2012-04-06
用格式化字符串啊

def formatdate(year, month, day):
s0='%d-%d-%d 00:00:00','YYYY-MM-DD HH24:MI:SS' %( year, month, day)
return s0

formatdate(1990,1,1 )

得到 '1990-1-1 00:00:00','YYYY-MM-DD HH24:MI:SS'
第4个回答  2012-04-08
用%格式化或者用+连接
相似回答