标签:
一、数字
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 #保留整数 floor division discards the fractional part
5
>>> 17 % 3 # 余数 the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
还可以使用**运算符计算幂乘方:
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
二、字符串
如果你前面带有\的字符被当作特殊字符,你可以使用原始字符串,方法是在第一个引号前面加上一个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
字符串可以跨多行。一种方法是使用三引号:"""..."""或者‘‘‘...‘‘‘。行尾换行符会被自动包含到字符串中,但是可以在行尾加上 \ (续行符)来避免这个行为。下面的示例:
print("""Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
将生成以下输出(注意,没有开始的第一行):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
字符串可以用 +操作符联接,也可以用* 操作符重复多次:
>>> # 3 times ‘un‘, followed by ‘ium‘
>>> 3 * ‘un‘ + ‘ium‘
‘unununium‘
三、索引
第一个字符的索引值为0
>>> word = ‘Python‘
>>> word[0] # character in position 0
‘P‘
>>> word[5] # character in position 5
‘n‘
索引也可以是负值,此时从右侧开始计数:
>>> word[-1] # last character
‘n‘
>>> word[-2] # second-last character
‘o‘
>>> word[-6]
‘P‘
注意,因为 -0 和 0 是一样的,负的索引从 -1 开始。
四、切片(列表、字符串)
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
‘Py‘
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
‘tho‘
省略的第一个索引默认为零,省略的第二个索引默认为切片的字符串的大小。
>>> word[:2] # character from the beginning to position 2 (excluded)
‘Py‘
>>> word[4:] # characters from position 4 (included) to the end
‘on‘
>>> word[-2:] # characters from the second-last (included) to the end
‘on‘
注、试图使用太大的索引会导致错误:
标签:
原文地址:http://www.cnblogs.com/yxtk/p/5691475.html