《Python编程:从入门到实践》(2016)(以下就称为《实践》了)这本书对字符串的介绍及其简单,学过C/C++的人就知道,字符串其实蛮复杂,从写法、格式到处理,处处都是值得留意的坑。
本文参照了utsuro老师的文章:https://www.cnblogs.com/utsuro/p/8657817.html。在《实践》这本书中,介绍了:
"This is a string."
'This is also a string.
这两种写法都是可以的。个人比较偏好用第一种写法,单个字符用单引号,包含单个字符的字符串用双引号,似乎与C有点串。简单验证下:print('a'== "a")(输出结果为True)。
1、双引号的情况:如果句子里含有单引号,用双引号可以避免使用转义符。
print("it's my life") 输出为:it's my life
2、三引号的情况:如果想表示:It's "C",I have "A" and "B"。 这种比较复杂的句式,用三引号是最简单的方式。
print(''' It's "C",I have "A" and "B"。''') 输出为:It's "C",I have "A" and "B"。
当然也可以用:
print(""" It's "C",I have "A" and "B"。""") 输出为:It's "C",I have "A" and "B"。
另外,如果这么写:
print(""" It's "C",
I have "A"
and "B"。""")
输出为:
It's "C",
I have "A"
and "B"。 免去了换行符。单三引号可以这么使用么:
print(''' It's "C",
I have "A"
and "B"。''') 输出同上。总体上,在不得不用三引号的时候,我个人比较建议用双三引号,似乎更美观些。
如果要输出:'I told my friend, "Python is my favorite language!"'
用print(""" 'I told my friend, "Python is my favorite language!"' """) 挺方便。
3、下列程序的输出是啥:
message= """ 'I told"""
print(message)
print(len(message))
答案: 'I told 8
在句子里,引号范围之类的空格也要算作字符数。字符串有专门的函数去掉空格。在《实践》这本书中,介绍了rstrip()、rstrip()和strip()函数。似乎没有函数能去掉中间多余的空格。
print(" py thon ")
print(" py thon ".strip())
输出:
py thon
py thon