您的位置:首页 > 移动开发 > 微信开发

练手小程序(三)

2015-11-30 09:55 639 查看
继续练习,走起!

今天的练习名字叫Mad Libs Generator,看名字很高大上,实际上就是提示用户输入一些信息,然后吧这些信息放到事前准备好的模板中在输出来就行了,要完成这个任务可以使用格式化输出,也可是使用string模块,既然要用到它们,就去学习一下吧

(资料来源:https://docs.python.org/2/library/string.html

string模块中主要需要学习的部分有三个:

string constants  也就是该模块中定义的一些常量
format 格式化字符串, 重点!!
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做了一个小脚本。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: