笨方法学python6-10

习题6:字符串和文本

作者提示:
1.尝试破坏代码 然后自己去修复。

代码

type_of_people = 10 #变量赋予
x=f"There are {type_of_people} type of people."  #变量赋予文本和嵌入的字符串
binary = "binary"  #变量赋予字符串,使用""
do_not = "don't"  #变量赋予字符串,使用""
y = f"Those who know {binary} and those who {do_not}." #变量赋予文本和嵌入的字符串
print(x)   #输出定义的格式化字符串
print(y)   #输出定义的格式化字符串
print(f"I said: {x}")  #把x作为参数传递给字符串打印,x是嵌套的变量也是被嵌套的。
print(f"I also said : '{y}'")  #y 同上
hilarious = "False"  #变量赋予布尔值
joke_evaluation = "Isn't that joke so funny?!{}."  #变量赋予文本和嵌入的字符串
print(joke_evaluation.format(hilarious))
#打印字符串,将布尔型作为参数,传递字符串的占位符

w = "This is the left side of..." #字符串赋值,使用""
e = "a string with right side."   #字符串赋值,使用""
print(w+e)  #打印合并两个字符串

在这里插入图片描述

知识点

  • Python可以通过文本里的双引号(““”)或者单引号(‘’)识别出来字符串。
  • 由一对单引号或双引号表示,作用相同,仅表示单行字符串。
    例如: “python单排之路”
  • 由一对三单引号或三双引号表示,可表示多行字符串。注意这不是前面说的多行注释。

    补充:单引,双引和三引,内部都可以加单引,双引和三引作为字符串的一部分,至于是 双引内含单引的字符串 还是 单引内含双引的字符串,这只是习惯问题。字符串中既可以有单引号也可以有双引号,单引号可以括双引号,双引号可以括单引号;单不能扩单,双不能括双。

x="python单排之路a"
y='python单排之路b'
z='''注意这不是
多行注释#
哟'''
print(x)
print(y)
print(z)

在这里插入图片描述

  • “f-string” 例: f"some stuff here {avariable}"
  • 解释w和e用+连起来就可以生成一个更长的字符串?
    Python提供5个字符串的基本操作符
操作符操作符
x+ y连接两个字符串x和y
n *x 或x *n复制n次字符串x
x in s如果x是s的子串,返回True,否则返回False
str[i]索引,返回第i个字符
Str[N:M]切片,返回索引第N到第M的子串,其中不包括M
  • 字符串类型的格式化,字符串格式化可以使得打印语句变得美观简洁。为了解决字符串和变量同时输出时的格式安排。python支持两周字符串格式化方法
    • 第一种了类C中printf()函数的时候方法。 “f-string”
      • 例: f"some stuff here {avariable}"

    • 第二种采用专门的str.format()格式化方法。用法如下:<模板字符串>.format(<逗号分隔的参数>)
      • 例:"{1}:计算机{0}的CPU占用率为{2}%".format(“2018-10-10”,“C”,10)。format()中参数的顺序依次传入字符串中槽{}的顺序内,默认顺序从左到右。


习题7:字符串和文本

作者提示:
1.尝试破坏代码 然后自己去修复。

代码

print("Mary had a little lamb.")  #打印语句
print("Its fleece was white as {}.".format('snow')) #打印语句,format格式化
print("And everywhere that Mary went.") #打印语句
print("."*10) #what'd that do? #打印复制10个点.

end1="C"  #变量赋值
end2="h"
end3="e"
end4="e"
end5="s"
end6="e"
end7="B"
end8="u"
end9="r"
end10="g"
end11="e"
end12="r" #变量赋值

#watch that comma at the end. try removing it to see what happen
print(end1+end2+end3+end4+end5+end5+end6,end="") #打印拼接的字符,并不换行
print(end7+end8+end9+end10+end11+end12) #打印拼接的字符串
PS C:\Users\WU> & python f:/python/笨方法学python3/Zedstudy/ex7.py
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
CheesseBurger

知识点

  • 单引号’ 一般被用来创建较短的字符串
  • end是print()函数的一个参数。end 是输出语句结束以后附加的字符串。作用是:不换行接上后面语句, Day1的作业也有说到。换行为’\n’。
  • 习题中 ‘snow’ 是一个内容为单词snow的字符串而已,变量名是不会带引号的,引号里面是字符串

破坏程序

  • 破坏程序一:一边的双引变成单引,语法错误。
print("Mary had a little lamb.')
PS C:\Users\WU\pyfile> python ex7.py
  File "C:\Users\WU\pyfile\ex7.py", line 1
    print("Mary had a little lamb.')
                                    ^
SyntaxError: EOL while scanning string literal
  • 破坏程序二:大写的Print,命名错误。
Print("Its fleece was white as {}.".format('snow'))
PS C:\Users\WU\pyfile> python ex7.py
Mary had a little lamb.
Traceback (most recent call last):
  File "C:\Users\WU\pyfile\ex7.py", line 2, in <module>
    Print("Its fleece was white as {}.".format('snow'))
NameError: name 'Print' is not defined
  • 破坏程序三:B变成空格,失败,没啥影响,照常打印,只是变成Cheesse urger
end7 = ""
PS C:\Users\WU\pyfile> python ex7.py
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
Cheeseurger
  • 破坏程序四:将默认值end=”” 变成 end=”end6”。结果就类似填充,不过知道end函数怎么用了。
print(end1+end2+end3+end4+end5+end6,end = 'end6')
PS C:\Users\WU\pyfile> python ex7.py
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
Cheeseend6Burger
  • 破坏程序五:使用format格式化字符串的时候,前面使用的{}符号给空格。结果反馈:{}符号是连续的,中间没有空格。
print("Its fleece was white as { }.".format('snow'))
PS C:\Users\WU\pyfile> python ex7.py
Mary had a little lamb.
Traceback (most recent call last):
  File "C:\Users\WU\pyfile\ex7.py", line 2, in <module>
    print("Its fleece was white as { }.".format('snow'))
KeyError: ' '
  • 破坏程序六:end8改为end81, 出现Nameerror。这种错误经常犯呃,使用变量时错误拼写变量名字。
print(end7+end81+end9+end10+end11+end12)
PS C:\Users\WU\pyfile> python ex7.py
Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
CheeseTraceback (most recent call last):
  File "C:\Users\WU\pyfile\ex7.py", line 21, in <module>
    print(end7+end81+end9+end10+end11+end12)
NameError: name 'end81' is not defined

习题8:字符串和文本

作者提示:
1.把破坏代码当做一个乐趣。

代码

formatter =  "{} {} {} {}"
print(formatter.format(1,2,3,4))
print(formatter.format('one','two','three','four'))
print(formatter.format(True,False,False,True))
print(formatter.format(formatter,formatter,formatter,formatter))
print(formatter.format(
    'Try your',
    "Own text time",
    'maybe a poem',
    'Or a song about fear'
))

formatter="{} {} {} {}"
print(formatter.format(1,2,3,4))
print(formatter.format(formatter,formatter,formatter,formatter))?
format在没有指定插入位置的话,format()括号内的{}参数是一个一个顺序插入{}里面的。
这里print(formatter.format(formatter,formatter,formatter,formatter))中里面的后4个formatter被当作变量传递给第一个formatter函数,也就是变成打印四个formatter。
简单来说就是每个{}中嵌入四个{},打印出来就是16个{}。

PS C:\Users\WU\pyfile> python ex8.py
1 2 3 4
one two three four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own text time maybe a poem Or a song about fear

知识点

  • True False 是 python 的关键字,所以不用加引号。Python一共有33个保留字(关键字),指被变成语言内部定义并保留使用的标识符。每种程序设计语言都有一套保留字,一般用来构成程序整体框架。表达关键值和具有结构性的复杂语义。
  • 其中True ,False ,None是大写开头的保留字,如果小写的话不是保留字,则是变量,按书上的说法准确来说是字符串。
  • format()使用方法的基本使用格式就是:<模板字符串>.format(<逗号分隔的参数>
  • 关键字
import keyword  #导入keyword模块
k = keyword.kwlist  #赋值,保留字列表
print("python保留字个数:"+str(len(k))+"个")
#打印,len()函数是得出数据长度
print(k)
PS C:\Users\WU> & python f:/python/笨方法学python3/Zedstudy/ex8.1.py
python保留字个数:36个
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 
'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

在这里插入图片描述

破坏程序

  • 破坏程序一:print语句多一个缩进,没有顶行编写。
formatter =  "{} {} {} {}"
    print(formatter.format(1,2,3,4))
print(formatter.format('one','two','three','four'))
print(formatter.format(True,False,False,True))
print(formatter.format(formatter,formatter,formatter,formatter))
print(formatter.format(
    'Try your',
    "Own text time",
    'maybe a poem',
    'Or a song about fear'
))
File "c:\Users\WU\pyfile\ex8.py", line 2
    print(formatter.format(1,2,3,4))
IndentationError: unexpected indent

度娘说IndentationError: unexpected indent最常见的原因就是没有对齐,所以可以检查自己是不是存在缩进等级的关系。

缩进表达所属关系,单层缩进代码属于之前最邻近的一行非缩进代码,多层缩进代码根据缩进关系决定所属范围。
缩进可以用Tab键实现,也可以用多个空格(一般是4个空格)实现,但两者不会用,建议采用4个空格反思书写代码。


习题9:打印打印

作者提示:
1.对于初学者,拼写错误占大部分的错误

代码

# 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 someting going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4Liunes if wu want,or 5 ,or 6
''')
PS C:\Users\WU\pyfile> python ex9.py
here are the days: Mon Tue Wed Thu Fri Sat Sun
Here are the months: Jan
Feb
Mar
Apr
May
Jun
Jul
Aug

There's someting going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4Liunes if wu want,or 5 ,or 6

知识点

  • 三引号”””之间不能有空格
    单引号,双引号,三引号之间的区别和用法可以参考 邓无邪博主文章]

总结:
①双引和单引一样。双引包单引号,单引包双引。多行字符用三单引或三双引。
②\n为换行意思,可以用来多行打印,但是看起来不美观,因此三引号就比较方便。
三引号还可以在内部加注释
③每一行字符串后面加一个\表示连字符,\不被打印,多用于单行字符过长时候换行

破坏程序

目前自己破坏选取位置:关键字,变量名,打印括号,赋值等号,加号逗号


习题10:那是什么

作者提示:
1.尝试破坏代码 然后自己去修复。

代码

tabby_cat = "\tI'm tabbed in." #\t Tab键,
persian_cat = "I'm split\non a line." #\n 换行
backslash_cat = "I'm \\ a \\ cat." #\\就是\

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(persian_cat)
print(backslash_cat)
print(fat_cat)
print("I am 6'2\" tall.") #将字符串的双引号转义
print('I am 6\'2" tall.') #将字符串的单引号转义print(tabby_cat)
PS C:\Users\WU\pyfile> python ex10.py
        I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.

I'll do a list:
        * Cat food
        * Fishies
        * Catnip
        * Grass

知识点

"I am 6'2\" tall." #将字符串中的双引号转义
'I am 6\'2" tall.' .#将字符串中的单引号转义
  • 使用反斜杠(\)将难以录入的字符放入字符串中,针对不同的符号有很多这样所谓的转义序列。
  • 斜杠(\)和 反斜杠(/)是不一样的字符,功能也完全不一样
  • 一种重要的转义序列是用来将单引号(’)和双引号(")转义.
转义字符功能
\续行符(行尾时)
\ \反斜杠(\)
\ ’单引号(’)
\ "双引号(")
\aASCII响铃符(BEL),蜂鸣,响铃
\bASCII退格符(BS),回退(Backspace),向后退一格
\e转义
\fASCII进纸符(FF),换页
\nASCII换行符(LF),换行,光标移动到下行行首
\N{name}Unicode数据库中的字符名,其中name是它的名字,仅Unicode使用
\rASCII回车符(CR),回车,光标移动到本行行首
\tASCII水平制表符(TAB)
\uxxxx值为16位十六进制值为 xxxx 的字符
\Uxxxxxxxx值为32位十六进制值为 xxxxxxxx 的字符
\vASCII垂直制表符(VT)
\ooo值为8进制值为 ooo 的字符
\xhh值为16进制值为 hh 的字符
\0NULL,什么都不做

我感觉目前知道\n是换行 \t是Tab 就ok了吧

破坏程序

  • 破坏程序一:双引号没有转义,语法错误。
tabby_cat = "\tI'm tabbed in." #\t Tab键,
persian_cat = "I'm split\non a line." #\n 换行
backslash_cat = "I'm \\ a \\ cat." #\\就是\

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(persian_cat)
print(backslash_cat)
print(fat_cat)
print("I am 6'2" tall.") #将字符串的双引号转义
print('I am 6\'2" tall.') #将字符串的单引号转义print(tabby_cat)
File "f:\python\笨方法学python3\Zedstudy\ex10.py", line 14
    print("I am 6'2" tall.") #将字符串的双引号转义
                     ^
SyntaxError: invalid syntax

因为外是双引,里面需要被转义的是双引而不是单引。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值