字符串格式化

我们在输出字符串的时候,如果想对输出的内容进行一些整理,比如把几段字符拼接起来,或者把一段字符插入到另一段字符中间,就需要用到字符串的格式化输出。

 

先从简单的开始,如果你想把两段字符连起来输出

str1 = 'good'

str2 = 'bye'

 

你可以

print str1 + str2

 

或者还可以把字符变量一个字符串相加

print 'very' + str1

print str1 + ' and ' + str2

 

但如果你想要把一个数字加到文字后面输出,比如这样

num = 18

print 'My age is' + num

程序就会报错。因为字符和数字不能直接用+相加。

 

一种解决方法是,用str()把数字转换成字符串

print 'My age is' + str(18)

num = 18

print 'My age is' + str(num)

 

还有一种方法,就是用%对字符串进行格式化

num = 18

print 'My age is %d' % num

输出的时候,%d会被%后面的值替换。输出

My age is 18

 

这里,%d只能用来替换整数。如果你想格式化的数值是小数,要用%f

print ‘Price is %f’ % 4.99

输出

Price is 4.990000

 

如果你想保留两位小数,需要在f前面加上条件:%.2f

print ‘Price is %.2f’ % 4.99

输出

Price is 4.99

 

另外,可以用%s来替换一段字符串

name = 'Crossin'

print '%s is a good teacher.' % name

输出

Crossin is a good teacher.

 

或者

print 'Today is %s.' % 'Friday' 

输出

Today is Friday.

 

注意区分:有引号的表示一段字符,没有引号的就是一个变量,这个变量可能是字符,也可能是数字,但一定要和%所表示的格式相一致。

 

现在,试试看用字符串格式化改进一下之前你写的小游戏。

比如你输了一个数字72,程序会回答你

72 is too small.

或者

Bingo, 72 is the right answer!

 

之前我们说到,可以用%来构造一个字符串,比如

print '%s is easy to learn' % 'Python'

 

有时候,仅仅代入一个值不能满足我们构造字符串的需要。假设你现在有一组学生成绩的数据,你要输出这些数据。在一行中,既要输出学生的姓名,又要输出他的成绩。例如

Mike‘s score is 87.

Lily‘s score is 95.

 

在python中,你可以这样实现:

print "%s's score is %d" % ('Mike', 87)

或者

name = ‘Lily’

score = 95

print "%s's score is %d" % (name, score)

 

无论你有多少个值需要代入字符串中进行格式化,只需要在字符串中的合适位置用对应格式的%表示,然后在后面的括号中按顺序提供代入的值就可以了。占位的%和括号中的值在数量上必须相等,类型也要匹配。

 

 

('Mike', 87)这种用()表示的一组数据在python中被称为元组(tuple),是python的一种基本数据结构,以后我们还会用到。

 

---转载自 Crossin的编程教室

 

StrFormatStuDemo

 

# coding=utf-8

str1 = 'good'
str2 = 'bye'
print str1 + str2

print 'very ' + str1
print str1 + ' and ' + str2

num = 23
print 'My age is ' + str(num)
print 'My age is %d'%num  # %d会被 %后面的值替换

print 'Price is %f'%4.99 #%d只能用来替换整数。如果你想格式化的数值是小数,要用%f
print 'Price is %.2f'%4.9900 #如果你想保留两位小数,需要在f前面加上条件:%.2f

name = "Long"
print '%s is a good man.'%name
print 'Today is %s'%'Wednesday'

 

 StrFormatStuDemo2

# coding=utf-8

print '%s is easy to learn' % 'Python'

print "%s's score is %d" % ('Mike', 87)

name = 'Lily'
score = 95
print "%s's score is %d" % (name, score)

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值