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

Python010

python 怎么在字符串中使用变量?,第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')

1. 使用连接符: +

1

2

world = "World"

print "Hello " + world + " ! "

2. 使用占位符来内插

1

2

world = "World"

print "Hello %s !" % world

3. 使用函数

1

2

3

li = ['my','name','is','bob']

mystr = ' '.join(li)

print mystr

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

1

2

3

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

有两种方案:(我是python3.6.3,如果有更多方法,欢迎留言)

假设你的变量名为X,并且为字符串。

格式化输出:print ("你想要输出的变量是: %s" % X)

字符串拼接(网上搜索,可用。感谢各位大佬):print ("你想要输出的变量是:" + X)