>>> import decimal >>> a = decimal.Decimal(9876) # 可以接受整数或字符串作为参数 >>> b = decimal.Decimal("54321.012345678987654321") # 小数必须用字符串! >>> a + b Decimal('64197.012345678987654321')
## 字符串 ##
### 单引号 ###
你可以将字符串放到单引号中,所有空白字符即空格和tab都回原封保留。
### 双引号 ###
双引号和单引号的效果完全相同。
### 三引号 ###
在指定多行字符串的时候可以利用三引号(`"""`或`'''`), 在三引号中还能自由的使用单引号和双引号. 一个例子:
'''This is a multi
This is the second
"What's your name?
He said "Bond, Jam
'''
### 转义字符 ###
假设你想要一个带单引号(')的字符串,你会怎么写呢?例如 `What's your name?`, 你不能写成 `'What's your name?'`,因为Python会搞不清字符串是从哪开始又是从哪结束。所以你需要告诉Python字符串中间的单引号并不是字符串的结束标志。
利用转义字符可以做到这点。将单引号替换成 `\'` —— 注意反斜杠,这样字符串就变成 `What's your name?` 了。另一个办法是使用双引号 `"What's your name?"` 。不过当你需要双引号的时候和单引号的情况类似,必须加上反斜杠 `\"`,而反斜杠也一样必须表示成 `\\` 。
如果你需要一个双行字符串呢? 一个办法是使用前面提到的三引号,或者使用换行的转义字符`\n`开始新的一行。
还有一个常用的转义字符是`\t`,用以输出制表符。Python中的转义字符很多,我只列举了最常用的。
另一个值得注意的地方是在一个字符串末尾的反斜杠表示这个字符串将被合并到下一行,例如:
1 2
"This is the first sentence.\ This is the second sentence."
上面的字符串等价于"This is the first sentence. This is the second sentence.".
### 原始字符串 ###
如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个原始字符串。原始字符串通过给字符串加上前缀r或R来指定。例如`r"Newlines are indicated by \n".`
### 字符串是不可变类型 ###
虽然这看起来像是一件坏事,但实际上它不是。我们将会在后面的程序中看到为什么我们说它不是一个缺点。
### 字面字符串连接 ###
如果你将两个字面字符串相邻,它们会被Python自动合并到一起。
例如`'What\'s ' 'your name?'`会变为`"What's your name?"`
#!/usr/bin/Python # Filename: str_format.py age = 25 name = 'Swaroop' print('{0} is {1} years old'.format(name, age)) print('Why is {0} playing with that Python?'.format(name))
输出:
1 2 3
$ Python str_format.py Swaroop is 25 years old Why is Swaroop playing with that Python?
要注意我们也可以使用字符串连接达到同样的目的: name + ' is ' + str(age) + ' years old'。但这种方式看起来太乱,容易出错。而且需要手动将变量转换为字符串,而format可以为我们代劳。最后, 使用format我们可以改变消息的形式,而不用修改传给format的变量,反之一样。
从Python 3.1开始,忽略字段名成为可能。即下面的用法是允许的:
1 2
>>> "{}{}{}".format("python","can","count") 'python can count'
format的本质就是将其参数替换到字符串中的格式说明符, 下面是一些更复杂的使用方式:
1 2 3 4 5 6 7 8 9 10 11
>>> '{0:.3}'.format(1/3) # 格式化规约,小数点后保留3位 '0.333' >>> '{0:_^11}'.format('hello') # 以下划线填充,中间对齐,宽度为11位长 '___hello___' >>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python') # 字段名格式化 'Swaroop wrote A Byte of Python' >>> stock = ['paper', 'envelopes', 'notepads', 'pens', 'paper clips'] >>> "We have {0[1]} and {0[2]} in stock".format(stock) 'We have envelopes and notepads in stock' >>> "math.pi == {0.pi} sys.maxunicode == {1.maxunicode}".format(math, sys) 'math.pi == 3.141592653589793 sys.maxunicode == 1114111'
>>> s = "The sword of truth" >>> "{0}".format(s) # default formatting "The sword of truth" >>> "{0:25}".format(s) # minimum width 25 'The sword of truth ' >>> "{0:>25}".format(s) # right align, minimum width 25 ' The sword of truth' >>> "{0:^25}".format(s) # center align, minimum width 25 ' The sword of truth ' >>> "{0:-^25}".format(s) # - fill, center align, minimum width 25 '---The sword of truth----' >>> "{0:.<25}".format(s) # . fill, left align, minimum width 25 'The sword of truth.......' >>> "{0:.10}".format(s) # maximum width 10 'The sword '
#!/usr/bin/python # Filename: using_list.py # This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase.') print('These items are:', end=' ') for item in shoplist: print(item, end=' ') print('\nI also have to buy rice.') shoplist.append('rice') print('My shopping list is now', shoplist)
print('I will sort my list now') shoplist.sort() print('Sorted shopping list is', shoplist)
print('The first item I will buy is', shoplist[0]) olditem = shoplist[0] del shoplist[0] print('I bought the', olditem) print('My shopping list is now', shoplist)
输出
1 2 3 4 5 6 7 8 9 10
$ python using_list.py I have 4 items to purchase. These items are: apple mango carrot banana I also have to buy rice. My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice'] I will sort my list now Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['banana', 'carrot', 'mango', 'rice']
zoo = ('python', 'elephant', 'penguin') # 注意小括号是可选的 print('Number of animals in the zoo is', len(zoo))
new_zoo = ('monkey', 'camel', zoo) print('Number of cages in the new zoo is', len(new_zoo)) print('All animals in new zoo are', new_zoo) print('Animals brought from old zoo are', new_zoo[2]) print('Last animal brought from old zoo is', new_zoo[2][2]) print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))
输出
1 2 3 4 5 6 7
$ python using_tuple.py Number of animals in the zoo is 3 Number of cages in the new zoo is 3 All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin')) Animals brought from old zoo are ('python', 'elephant', 'penguin') Last animal brought from old zoo is penguin Number of animals in the new zoo is 5
# 删除一个键值对 del ab['Spammer'] print('\nThere are {0} contacts in the address-book\n'.format(len(ab))) for name, address in ab.items(): print('Contact {0} at {1}'.format(name, address))
$ python using_dict.py Swaroop's address is swaroop@swaroopch.com There are 3 contacts in the address-book Contact Swaroop at swaroop@swaroopch.com Contact Matsumoto at matz@ruby-lang.org Contact Larry at larry@wall.org Guido's address is guido@python.org
# Slicing on a list print('Item 1 to 3 is', shoplist[1:3]) print('Item 2 to end is', shoplist[2:]) print('Item 1 to -1 is', shoplist[1:-1]) print('Item start to end is', shoplist[:]) # 全切片
# Slicing on a string print('characters 1 to 3 is', name[1:3]) print('characters 2 to end is', name[2:]) print('characters 1 to -1 is', name[1:-1]) print('characters start to end is', name[:])
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
$ python seq.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Character 0 is s Item 1 to 3 is ['mango', 'carrot'] Item 2 to end is ['carrot', 'banana'] Item 1 to -1 is ['mango', 'carrot'] Item start to end is ['apple', 'mango', 'carrot', 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop
>>> list(range(3, 6)) # 使用分离的参数正常调用 [3, 4, 5] >>> list(range([3, 6])) # 直接使用一个列表作为range()函数的参数会出错 Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'list' object cannot be interpreted as an integer >>> args = [3, 6] >>> list(range(*args)) # 通过解包列表参数调用 [3, 4, 5]
同样的, 字典可以通过 ** 操作符来释放参数:
1 2 3 4 5 6 7 8
>>> defparrot(voltage, state='a stiff', action='voom'): ... print("-- This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "volts through it.", end=' ') ... print("E's", state, "!") ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
name = 'Swaroop'# 这是一个字符串对象 if name.startswith('Swa'): print('Yes, the string starts with "Swa"') if'a'in name: print('Yes, it contains the string "a"') if name.find('war') != -1: print('Yes, it contains the string "war"') delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print(delimiter.join(mylist))
输出
1 2 3 4 5
$ python str_methods.py Yes, the string starts with "Swa" Yes, it contains the string "a" Yes, it contains the string "war" Brazil_*_Russia_*_India_*_China