笨方法自学python(五)-字符串和文本

字符串和文本

在这章习题中我们将使用复杂的字符串来建立一系列的变量,从中你将学到它们的用途。首先我们解释一下字符串是什么 东西。
字符串通常是指你想要展示给别人的、或者是你想要从程序里“导出”的一小段字符。Python 可以通过文本里的双引号 " 或者单引号 ’ 识别出字符串来。这在你以前的 print 练习中你已经见过很多次了。如果你把单引号或者双引号括起来的文本放到 print 后面,它们就会被 python 打印出来。
字符串可以包含格式化字符 %s,这个你之前也见过的。你只要将格式化的变量放到字符串中,再紧跟着一个百分号 % (percent),再紧跟着变量名即可。唯一要
注意的地方,是如果你想要在字符串中通过格式化字符放入多个变量的时候,你需要将变量放到 ( ) 圆括号(parenthesis)中,而且变量之间用 , 逗号(comma)隔开。

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print (x)
print (y)
print ("I said: %r." % x)
print ("I also said: '%s'." % y)
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print ( joke_evaluation  % hilarious)
w = "This is the left side of..."
e = "a string with a right side."
print (w + e)

在这里犯了一个错误,(我用中文格式打出来的,会报错
在这里插入图片描述
运行结果:
在这里插入图片描述

更多打印练习

formatter = "%r %r %r %r"
print (formatter % (1, 2, 3, 4))
print (formatter % ("one", "two", "three", "four"))
print (formatter % (True, False, False, True))
print (formatter % (formatter, formatter, formatter, formatter))
print (formatter % (
 "I had this thing.",
 "That you could type up right.",
 "But it didn't sing.",
 "So I said goodnight."
))

运行结果
在这里插入图片描述

打印练习

# Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print ("Here are the days: ", days)
print ("Here are the months: ", months)
print ("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
""")

运行结果

在这里插入图片描述
\n是换行,下节会讲

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值