少说话多写代码之Python学习004——看看字符串怎么用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yysyangyangyangshan/article/details/81545562

学习新的语言,没有别的捷径,就得从最简单的开始练习。我们先从字符串开始看看。

直接上代码如下。

#!/usr/bin/python
#coding :utf-8

from string import Template

print("今天逛了广州小蛮腰!");

#字符串格式化
format= "我本将心向%s,奈何明月照%s"
values=('明月','沟渠')
print(format % values)

#格式化字符串,替换
str=Template('$r,蜀道难,难于上青天')
str=str.substitute(r='噫吁嚱')
print(str)

#格式化煮字符串,插入$
istr= Template('这个符号$$叫:$s!')
istr= istr.substitute(s='到了,US刀啦')
print(istr)

#格式化煮字符串,使用字段赋值
dstr=Template ('阁下是 $area $name ?')
dic={}
dic['area']='华山'
dic['name']='岳不群'
dstr=dstr.substitute(dic)
print(dstr)

如上代码运行结果如下,

今天逛了广州小蛮腰!
我本将心向明月,奈何明月照沟渠
噫吁嚱,蜀道难,难于上青天
这个符号$叫:到了,US刀啦!
阁下是 华山 岳不群 ?

工程文件下载:https://download.csdn.net/download/yysyangyangyangshan/10594421

猜你喜欢

转载自blog.csdn.net/yysyangyangyangshan/article/details/81545562