master
/ 5.2.1 字符串的创建.ipynb

5.2.1 字符串的创建.ipynb @masterview markup · raw · history · blame

Notebook

字符串的创建

5.8 字符串的创建.jpg

1. 将一个或多个字符放在引号中。

用单引号创建的字符串中可以包含双引号

In [3]:
s_string = '这是字符串,允许包含"双引号" '
print(s_string)
这是字符串,允许包含"双引号" 

用双引号创建的字符串中可以包含单引号

In [6]:
d_string = "这是字符串,允许包含'单引号' "
print(d_string)
这是字符串,允许包含'单引号' 

用三个引号括起的字符串可以包含单引号、双引号和回车符,即可以保留字符串的格式。

In [7]:
tri_string = '''这是字符串,允许包含"双引号"和'单引号' '''
print(tri_string)
这是字符串,允许包含"双引号"和'单引号' 
In [4]:
poem = ''' 
驿外断桥边,寂寞开无主。
已是黄昏独自愁,更著风和雨。
无意苦争春,一任群芳妒。
零落成泥碾作尘,只有香如故。
'''
print(poem)

2. 用 str() 将其他对象转为字符串

In [8]:
num_str = str(371)   # 整数转字符串
sum_of_cube = 0      # 累加器初值0
for i in num_str:    # 遍历字符串中的字符
    sum_of_cube = sum_of_cube + int(i)** 3  # 各位上数字的3次方加和
print(sum_of_cube)   # 371
371

3. 读文件生成字符串

遍历用open() 函数创建的文件对象,每次循环把其中一行读取为一个以换行符“\n”结尾的字符串。

91.1748 81.64305 93.0148 84.629425 88.4625 ... 86.8273 90.89875 95.95105 60
In [6]:
# 每个循环读取到的数据分别为:

"91.1748\n"
"91.1748\n"
"81.64305\n"
"93.0148
"84.629425\n"
"88.4625\n"
...
"86.8273\n"
"90.89875\n"
"95.95105\n"
"60\n"

若文件中不包含空行,即每次读取的数据都是__非空字符串__的话,可以用float()函数将其转为浮点数:

In [1]:
print(float("91.1748\n"))  # 可得到浮点数91.1748,float()函数可自动去除字符串末尾的换行符“\n”
In [2]:
print(float("91.1748\n".strip()))  # 也可先用strip()去除字符串末尾的换行符“\n”
In [9]:
total, num = 0, 0                           # 总成绩初值为0,成绩数量初值0
with open('images/ch5/sc.txt') as score:  # 打开文本文件,创建文件对象命名为score
	for line in score:                      # 遍历文件,每行数据转浮点数累加得到总成绩
		total = total + float(line)         # 每行数据转浮点数累加得到总成绩
		num = num + 1                       # 统计成绩数量
avg = total / num                           # 计算平均成绩
print(round(avg, 2))                        # 79.66,保留2位小数
85.9
In [6]:
with open('images/ch5/sc.txt') as score:  # 打开文本文件,创建文件对象命名为score
	score = [float(line) for line in score]   # 列表推导式,每行数据转浮点数构建一个列表
avg = sum(score) / len(score)                  # 计算平均成绩
print(round(avg, 2))                           # 79.66,保留2位小数
85.9
列表推导式的具体用法可参考列表章节内容。