Learn to Code

《笨办法学Python3》练习六:字符串和文本

2019-02-28  本文已影响0人  雨开Ame

练习代码

type_of_people = 10
x = f"There are {type_of_people} types 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}")
print(f"I also said: '{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 a right side."

print(w + e)

Study Drills

  1. Go through this program and write a comment above each line explaining it.
type_of_people = 10
x = f"There are {type_of_people} types 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}") # 嵌套格式化字符串
print(f"I also said: '{y}'") # 将格式化字符串有转换成字符串输出

hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious)) # 使用format方法格式化输出字符串

w = "this is the left side of..."
e = "a string with a right side."

print(w + e) # 使用 + 连接字符串
  1. Find all the places where a string is put inside a string. There are four places.
type_of_people = 10
x = f"There are {type_of_people} types 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}") # ③
print(f"I also said: '{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 a right side."

print(w + e)
  1. Are you sure there are only four places? How do you know? Maybe I like lying.

  2. Explain why adding the two strings w and e with + makes a longer string.

运算符重载。而重载的本质是因为Python中一切变量都是对象,连接两个string类型变量的+实际上就是调用 String 对象从Object 那里继承来的Object.__add__(self, other)方法。w+e等价于w.__add__(e)。我们也可以在自己创建的class里重写这个方法。

个人补充

  1. 还是接着说上面第4题的字符串连接用+的问题。

由于Python中字符串是 immutable(不可变) 的,所以w+e并不是将e加到w后面,而是分别拷贝ew,然后返回一个新的string we = w + e,这样不但产生了多余操作,还占用了多余的空间,所以这个方法的时间和空间效率是低下的,会造成程序运行慢。
用以代替此方法的是"".join(iterable)iterable指可迭代对象:liststring等。这里我们就可以改为"".join([w, e]),减少了拷贝次数。
当然还有其它方法,详见:
Efficient String Concatenation in Python
介绍了6种字符串连接的方法并在时空层面上比较了6种方法。
The Python String Concatenation Shootout
同上,但是得出一个结论:如果只是单纯连接字符串而不涉及列表操作,+仍可优先来使用(效率反而比join高),若涉及列表操作,则推荐用join方法。

  1. format()格式化方法与f"loremipsum..."格式化字符串的使用进阶

请仔细阅读 官方文档 - Format String Syntax 格式化字符串语法

上一篇 下一篇

猜你喜欢

热点阅读