練手小程序(三)

繼續練習,走起!

今天的練習名字叫Mad Libs Generator,看名字很高大上,實際上就是提示用戶輸入一些信息,然後吧這些信息放到事前準備好的模板中在輸出來就行了,要完成這個任務可以使用格式化輸出,也可是使用string模塊,既然要用到它們,就去學習一下吧微笑(資料來源:https://docs.python.org/2/library/string.html

string模塊中主要需要學習的部分有三個:

  1. string constants  也就是該模塊中定義的一些常量
  2. format 格式化字符串, 重點!!
  3. template string 模板替換

其它的一些保留但不推薦使用的函數比如string.split(s,[sep,[maxsplit]])等,就不詳細瞭解了,只需要知道有這麼個事就好了(因爲直接使用s.split()函數就好微笑

在python交互解釋器中來學習一下string 模塊吧。

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'

以上是部分string 常量,在這裏不一一列出。

內置的string類和unicide類可以直接使用formate函數,不需要導入string模塊也可以函數格式:

s.format(format_string,*args, **kwargs)
下面通過例子來說明:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 需要python 2.7+
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 解包參數序列
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 參數的序號可以重複使用!!
'abracadabra'
以上是format方法的基本用法,接受一系列位置參數然後分別替換目標字符串中相應的位置

接下來是format方法接受關鍵字參數的例子:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
這樣的代碼雖然看起來複雜一點,但是可讀性更好!

formate的參數還可以是參數的屬性,序列的元素等等

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point(object):
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...<pre name="code" class="python">#!/usr/bin/env python
# _*_ coding: utf-8 _*_

def get_users_input():
    "get the users' imput from commond line"
    # the list of key words need to input
    key_words = ["name", "sex"]    
    context = {}    # a dictionary used for storge the information
    for key in key_words:
        info = "Input a guy's %s: " % key
        context[key] = raw_input(info)
    return context


template = """
{name} is a {sex}.
"""

if __name__ == "__main__":
    context = get_users_input()
    output = template.format(**context)
    print(output)

>>> str(Point(4, 2))'Point(4, 2)'


以上兩個例子,第一個format的參數是內置類型虛數的兩個屬性,另一個例子中format的參數是自定義類型Point的兩個屬性

下面這個例子format的參數是一個元組中的元素

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

關於更多的format使用細節請參照官方文檔。

下面我們用剛剛學到的知識來解決今天的小練習。

#!/usr/bin/env python
# _*_ coding: utf-8 _*_

def get_users_input():
    "get the users' imput from commond line"
    # the list of key words need to input
    key_words = ["name", "sex"]    
    context = {}    # a dictionary used for storge the information
    for key in key_words:
        info = "Input a guy's %s: " % key
        context[key] = raw_input(info)
    return context


template = """
{name} is a {sex}.
"""

if __name__ == "__main__":
    context = get_users_input()
    output = template.format(**context)
    print(output)
以上,簡單的用format做了一個小腳本。




發佈了30 篇原創文章 · 獲贊 26 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章