# 5. 字符串和文本




### 什么是字符串

目前为止我们已经打印了不少的字符串了。那么什么是字符串呢?

在python里，字符串往往表现为用单引号```''```或者是双引号```""```包裹起来的一些文字。这些文字便于人类阅读，往往可以展示给我们程序的用户阅读。

下面代码里s1,s2都是字符串。

```python

s1 = '本次测试覆盖了100个模块'
s2 = "本次测试运行了100个用例"

```

### f-string

我们经常需要在字符串中包含一些变量，这样可以让字符串变得更加动态，不同变量的取值可以生成不同的字符串。

python 3.6 之后引入了f-string的概念，可以非常方便的在字符串中包含变量。比如下面的例子。

```python

module_count = 3
f"本次测试覆盖了{module_count}个模块"

```

另外python还支持.format()语法，我们后面通过代码去理解


### 背景

这一节里，我们把上一节的内容使用f-string来重新实现一下，逻辑和输出保持不变，用开发领域的术语来说，叫做"重构"。

### 代码实现

新建名为```report_with_f_string.py```，内容如下

```python
# 打印出本次测试的测试结果
# A: 27/30 B: 40/40 C: 30/30
module_count = 3

case_count_of_module_a = 30.0
success_case_count_of_module_a = 27

case_count_of_module_b = 40.0
success_case_count_of_module_b = 40

case_count_of_module_c = 30.0
success_case_count_of_module_c = 30

print(f"本次测试覆盖了{module_count}个模块")
print(f"测试用例总数为: {case_count_of_module_a + case_count_of_module_b + case_count_of_module_c}")
print(f"执行的测试用例总数为: {case_count_of_module_a + case_count_of_module_b + case_count_of_module_c}")
print(f"用例最多的模块是B模块，B模块比A模块多出的用例数为: {case_count_of_module_b - case_count_of_module_a}")
print(f'A模块执行成功{success_case_count_of_module_a}个用例，执行失败的用例数为{case_count_of_module_a - success_case_count_of_module_a}')
print('A模块用例通过率为百分之{}'.format(success_case_count_of_module_a / case_count_of_module_a * 100))
print('B模块的用例全部执行通过， 通过率为百分之{}'.format((success_case_count_of_module_b / case_count_of_module_b) * 100))
print('C模块的用例全部执行通过， 通过率为百分之{}'.format((success_case_count_of_module_b / case_count_of_module_b) * 100))

test_type = '回归测试'
test_result = '不通过'

# 结束打印
print(test_type + test_result)
```

### 运行

在命令行中使用下面的命令去执行代码

```
$python report_with_f_string.py

```

### 你应该可以看到

如果没有出错的话，你应该可以看到命令行窗口显示如下的内容

```
本次测试覆盖了3个模块
测试用例总数为: 100.0
执行的测试用例总数为: 100.0
用例最多的模块是B模块，B模块比A模块多出的用例数为: 10.0
A模块执行成功27个用例，执行失败的用例数为3.0
A模块用例通过率为百分之90.0
B模块的用例全部执行通过， 通过率为百分之100.0
C模块的用例全部执行通过， 通过率为百分之100.0
回归测试不通过
```

### 常见问题

* 为什么有时候字符串用单引号有时候又用双引号？ 一般情况下用双引号就足够了，不过有时候我们需要打印出单引号，这时候把单引号放到双引号内就可以了,反之亦然。




原始封面

![课程图片](https://images.unsplash.com/photo-1503551723145-6c040742065b-v2?w=300)


