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
3.3. unicode 字元串
>>> current = u'¥'
>>> print current
¥
>>> current.encode('utf-8')
'\xef\xbf\xa5'
>>>