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

2025年01月11日 17:10
有5个网友回答
网友(1):

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')

网友(2):

使用正则表达式,将里面的字符串提取出来。参考正则表达式模块(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

网友(3):

"select * from usb where time between %s and %s" %('2012-04-06 00:00:00','2012-04-06 23:59:59')

网友(4):

用格式化字符串啊

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'

网友(5):

用%格式化或者用+连接