
3.1.2 字符串类型
字符串是Python编程语言中最常用的数据类型,可以使用单引号(')或双引号(")来创建字符串。需要注意的是,Python不支持单字符类型,单字符在Python中也是作为一个字符串使用。
1. 普通字符串实例
单击“开始”菜单,打开Python 3.6.5 Shell软件,然后在菜单栏中选择File→New File命令,创建一个Python文件,并命名为“Python3-2.py”,然后输入以下代码:

在菜单栏中选择Run→Run Module命令或按键盘上的F5键,运行程序代码,结果选择如图3.3所示。

图3.3 字符串
在需要在字符串中使用特殊字符时,Python用反斜杠(\)转义字符。转义字符及意义如表3.2所示。
表3.2 转义字符及意义

Python支持格式化字符串的输出,尽管这样可能会用到非常复杂的表达式,但最简单的用法是将一个值插入一个有字符串格式符%s的字符串中。
提醒 在Python中,字符串格式化使用与C中sprintf()函数一样的语法。
2. 格式化字符串的输出实例
单击“开始”菜单,打开Python 3.6.5 Shell软件,然后输入以下代码:

按Enter键,就可以运行代码,如图3.4所示。

图3.4 格式化字符串的输出
利用input()函数可以进行动态输入,该函数的语法结构如下:

其中,参数prompt是提示信息。input()函数接受一个标准输入数据,返回为string类型。
3. input()函数实例
单击“开始”菜单,打开Python 3.6.5 Shell软件,然后在菜单栏中选择File→New File命令,创建一个Python文件,并命名为Python3-3.py,然后输入以下代码:

这里需要注意,input()函数默认数据类型是字符串型,要想输出数值型,需要使用int()函数进行数据类型转换。
在菜单栏中选择Run→Run Module命令或按键盘上的F5键,就可以运行程序代码,这时程序要求输入您的名称,如图3.5所示。

图3.5 程序要求输入您的名称
假如这里输入“李哲”,然后按Enter键,这时程序要求输入您的年龄,如图3.6所示。

图3.6 程序要求输入您的年龄
假如这里输入“8”,然后按Enter键,这时程序要求输入您的爱好,如图3.7所示。

图3.7 程序要求输入您的爱好
假如这里输入“围棋、跑步、跳高”,然后按Enter键,这时程序就会显示输入的名称、年龄和爱好信息,如图3.8所示。

图3.8 格式化显示输入的信息
Python的字符串格式化符号及意义如表3.3所示。
表3.3 字符串格式化符号及意义
