您的位置:首页 > 编程语言 > Python开发

趣学python第3章字符串2把值插入到某位置

2018-01-21 21:21 218 查看
趣学python第3章字符串2把值插入到某位置

1.用%s把值嵌入到字符串里

mysorce = 100
message = 'i scored %s point.'
print(message % mysorce)

===================== RESTART: C:/Python27/lianxi/31.py =====================

i scored 100 point.
对于同一个%s占位符可以用不同的变量来穿给它不同的值。

#!usr/bin/env python
#coding:utf-8
mysorce = 100
mysorce2 = 99
message = 'i scored %s point in %s'
kemu1 = '语文'
kemu2 = '数学'
print(message % (mysorce ,kemu1))
print(message % (mysorce2 ,kemu2))

运行结果
===================== RESTART: C:/Python27/lianxi/31.py =====================

i scored 100 point in 语文

i scored 99 point in 数学

用括号将多个替换的变量括起来,值排放的顺序就是它们在字符中被引用到的顺序。

2.字符串乘法

spaces = ' '*25
print('%s 12 butts wynd' % spaces)

===================== RESTART: C:/Python27/lianxi/31.py =====================

                          12 butts wynd

乘法用*,小键盘上的星花标记。

low = 12
fr =11
pay =low * fr
fred = "i should pay for %s"
print (fred *2)
space = ' '*25
print ('%s 12 butts wynd '% space)
print ('%s twinklebottom hesth' % space)
print (pay)
print ()
print ('dear sir' )
print ()
print ('%s twinkle bottom hesth' % space)变量的乘法没有什么不同,这里重要的是字符串的乘法,它可以让字符串复制。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 字符串
相关文章推荐