Python string interpolation implementation

后端 未结 3 808
盖世英雄少女心
盖世英雄少女心 2020-12-10 16:53

[EDIT 00]: I\'ve edited several times the post and now even the title, please read below.

I just learned about the format string method, and its use with dictionarie

3条回答
  •  一向
    一向 (楼主)
    2020-12-10 17:37

    Language Design Is Not Just Solving Puzzles: ;)

    http://www.artima.com/forums/flat.jsp?forum=106&thread=147358

    Edit: PEP-0498 solves this issue!

    The Template class from the string module, also does what I need (but more similar to the string format method), in the end it also has the readability I seek, it also has the recommended explicitness, it's in the Standard Library and it can also be easily customized and extended.

    http://docs.python.org/2/library/string.html?highlight=template#string.Template

    from string import Template
    
    name = 'Renata'
    place = 'hospital'
    job = 'Dr.'
    how = 'glad'
    header = '\nTo Ms. {name}:'
    
    letter = Template("""
    Hello Ms. $name.
    
    I'm glad to inform, you've been
    accepted in our $place, and $job Red
    will ${how}ly recieve you tomorrow morning.
    """)
    
    print header.format(**vars())
    print letter.substitute(vars())
    

    The funny thing is that now I'm getting more fond of using {} instead of $ and I still like the string_interpolation module I came up with, because it's less typing than either one in the long run. LOL!

    Run the code here:

    http://labs.codecademy.com/BE3n/3#:workspace

提交回复
热议问题