注释 #
字面常量 数字:5、1.23 文本:这是一串文本 或 This is a string
数字 整型与浮点型
单引号 所有引号内的空间,诸如空格与制表符,都将按原样保留
双引号 与当引号工作机制相同
三引号 指定多行字符串 """ 或 ''' 。可以在三引号之间自由的使用单引号与多引号。
格式化方法 format()方法将每个参数替换至格式所在的位置
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
注意:python从0开始计数,数字只是一个可选选项
age = 20
name = 'Swaroop'
print('{} was {} years old when he wrote this book'.format(name, age))
输出为:Swaroop was 20 years old when he wrote this book
format方法自动完成转换至字符串的工作。
一些更详细的格式:
print('{0:.3f}'.format(1.0/3)) #0.333
print('{0:_^12}'.format('hello')) #___hello____ 使用下划线填充文本,并保持文字处于中间位置
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte Of Python')) #基于关键词输出
print总是会以一个看不见的“新一行”字符(\n)结尾
为防止打印过程中出现这一换行符,可以通过 end 指定其以空白结尾:
print('a', end='')
print('b', end='')
输出:ab
转义序列
'What\'s your name?'
'This is the first line\nThis is the second line'
放置在末尾的反斜杠表示字符串将在下一行继续,但不会添加新的一行:
“This is the first sentence.\
This is the second sentence”
相当于“This is the first sentence. This is the second sentence”
原始字符串 r 或 R
处理正则表达式时应全程使用原始字符串
变量
命名:
- 第一个字符:字母或下划线(_)
- 其他部分:字母、下划线(_)、数字(0-9)
- 标识符名称区分大小写
数据类型
对象
Python将程序的任何内容统称为对象,Python是强面向对象的。
物理行:你在编写程序时所看到的内容。
逻辑行:Python所能看到的单个语句。
显式行连接:
s = 'This is a string. \
This continues the string.'
print(s)
输出:This is a string. This continues the string.
缩进
使用四个空格来缩进