3. python 数字与字符串
词汇:
plus +
subtract -
mulitply *
division /
divisor 除数
reminder 余数
power ** 幂
equal =
fraction 小数部分
complex number 复数
decimal 十进制
parenthesis 圆括号
square parenthesis 方括号
brace 花括号
int integer 整数
float 浮点数
single quotes ‘ ’
double quotes ” “
blackslash 、
raw string r
triple-quotes ”“” “”“
unicode u
3.1 数字及运算
>>> 3 + 1
4
>>> 3 * (2 + 1)
9
>>> 7 / 2 # division
3
>>> 7 % 2
1 # reminder
>>> 7.0 / 2 # float division
3.5
>>> 7.0 // 2
3.0
>>> 2**10 # power
1024
>>> price = 10
>>> tax = price * 12 / 100
>>> print price, tax
10 1
>>> print price + tax
<pre name="code" class="python" style="font-size: 18px;">11
内部变量 “_" 会默认获得最后一个计算的值,被print函数引用的除外
>>> 2 + 3
5
>>> _
5
>>> a = 6
>>> a * 3
18
>>> _
18
>>> print a * 10
60
>>> _
18
>>>
3.2 字符
单引号与双引号用法:
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
raw string, 用r字符可以屏蔽掉特殊字符
>>> print 'C:\some\name' # here \n means newline!
C:\some
ame
>>> print r'C:\some\name' # note the r before the quote
C:\some\name
triple-quotes 可以让一个字符串跨行
print """\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
字符串可以用加号来互相连接, 乘以数字实现重复次数
>>> 'a good' + ' day' + '!'*3
'a good day!!!'
字符串可以用分片的方式抽取部分或全部字符串。首个字符对应第0位。 word[<此位开始显示:<显示到此位以前>]
>>> word = 'agoodday'
>>> word[1:3]
'go'
>>> word[:3]
'ago'
>>> word[-2]
'a'
>>> word[-1]
'y'
len() 字符串的函数, 用来计算字符串长度
>>> len(word)
8
>>> current = u'¥'
>>> print current
¥
>>> current.encode('utf-8')
'\xef\xbf\xa5'
>>>