It is a challenge record of Language processing 100 knock 2015. The environment is Ubuntu 16.04 LTS + Python 3.5.2 : : Anaconda 4.1.1 (64-bit). Click here for a list of past knocks (http://qiita.com/segavvy/items/fb50ba8097d59475f760).
Implement a function that takes arguments x, y, z and returns the string "y at x is z". Furthermore, set x = 12, y = "temperature", z = 22.4, and check the execution result.
The finished code:
main.py
# coding: utf-8
def format_string(x, y, z):
'''Argument x, y,Receives z and returns the string "y at x is z"
argument:
x, y, z --Parameters to embed
Return value:
Formatted string
'''
return '{hour}of time{target}Is{value}'.format(hour=x, target=y, value=z)
#test
x = 12
y = 'temperature'
z = 22.4
print(format_string(x, y, z))
Execution result:
Terminal
The temperature at 12:00 is 22.4
How to specify str.format ()
is [Format specification string grammar](http://docs .python.jp/3/library/string.html#formatstrings) has an explanation. If you don't use it, it's hard to remember.
Also, there is string.Template
class. This may be closer to the intention of the question, so I will write it here as well.
The finished code:
main2.py
# coding: utf-8
from string import Template
def format_string(x, y, z):
'''Argument x, y,Receives z and returns the string "y at x is z"
argument:
x, y, z --Parameters to embed
Return value:
Formatted string
'''
s = Template('$hour$target is$value')
return s.substitute(hour=x, target=y, value=z)
#test
x = 12
y = 'temperature'
z = 22.4
print(format_string(x, y, z))
Execution result:
Terminal
The temperature at 12:00 is 22.4
That's all for the 8th knock. If you have any mistakes, I would appreciate it if you could point them out.
Recommended Posts