练手小程序(三)

本文介绍了Python的string模块,重点学习了format字符串格式化和template模板替换。通过实例演示了如何使用这些功能来创建Mad Libs Generator,这是一个提示用户输入信息并将其插入预定义模板的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继续练习,走起!

今天的练习名字叫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做了一个小脚本。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值