1、注释
python中注释以#开头,举个栗子。
print("hello world") #这里就是注释
2、数字
数字主要分为两种:整数和浮点数。
有关整数的例子即 2 ,它只是一个整数。
有关浮点数(Floating Point Numbers,在英文中也会简写为 floats ) 的例子是 3.23 或
52.3E-4 。其中, E 表示 10 的幂。在这里, 52.3E-4 表示 52.3 * 10^-4 。
注意:没有单独的 long 类型。 int 类型可以指任何大小的整数。
3、引号
(1)单引号
可以使用单引号来指定一个字符串,如:’this is a string’。
(2)双引号
被双引号包括的字符串和被单引号括起的字符串其工作机制完全相同。
(3)三引号
可以通过使用三个引号—— “”” 或 ”’ 来指定多行字符串。你可以在三引号之间自由地
使用单引号与双引号。举个栗子:
'''这是一段多行字符串。这是它的第一行。
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
4、格式化方法
将以下内容保存为文件 str_format.py :
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
输出:
$ python str_format.py
Swaroop was 20 years old when he wrote this book
Why is Swaroop playing with that python?
Python 中 format 方法所做的事情便是将每个参数值替换至格式所在的位置。这之中可以有
更详细的格式,例如:
# 对于浮点数 '0.333' 保留小数点(.)后三位
print('{0:.3f}'.format(1.0/3))
# 使用下划线填充文本,并保持文字处于中间位置
# 使用 (^) 定义 '___hello___'字符串长度为 11
print('{0:_^11}'.format('hello'))
# 基于关键词输出 'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))
输出:
0.333
___hello___
Swaroop wrote A Byte of Python
由于我们正在讨论格式问题,就要注意 print 总是会以一个不可见的“新一行”字符(\n )
结尾,因此重复调用 print 将会在相互独立的一行中分别打印。为防止打印过程中出现这一
换行符,你可以通过 end 指定其应以空白结尾:
print('a', end='')
print('b', end='')
输出:
ab
或者你通过 end 指定以空格结尾:
print('a', end=' ')
print('b', end=' ')
print('c')
输出:
a b c