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

1. 使用连接符: + world = "World"print "Hello " + world + " ! "2. 使用占位符来内插 world = "World"print "Hello %s !" % world3. 使用函数 li = ['my','name','is','bob']mystr = ' '.join(li)print mystr 上面的语句中字符串是作为参数传入的,可以直接用变量替换:...
python 怎么在字符串中使用变量?
1. 使用连接符: +
world = "World"print "Hello " + world + " ! "2. 使用占位符来内插
world = "World"print "Hello %s !" % world3. 使用函数
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')2015-08-26
使用正则表达式,将里面的字符串提取出来。参考正则表达式模块(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,day2012-04-06
"select * from usb where time between %s and %s" %('2012-04-06 00:00:00','2012-04-06 23:59:59')2012-04-12
用格式化字符串啊

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'2012-04-06
用%格式化或者用+连接2012-04-08
mengvlog 阅读 7 次 更新于 2025-07-19 06:32:52 我来答关注问题0
檬味博客在线解答立即免费咨询

Python相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部