>>> import decimal >>> a = decimal.Decimal(9876) # 可以接受整数或字符串作为参数 >>> b = decimal.Decimal("54321.012345678987654321") # 小数必须用字符串! >>> a + b Decimal('64197.012345678987654321')
#!/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