Task:
Given a number,
3
for example, return a string with a murmur:"1 sheep...2 sheep...3 sheep..."
Note:
You will always receive a positive integer.
可以直接用for和字符串拼接 ,不过需要先将range(1,n+1)字符串化,否则string+int会报错。
def count_sheep(n):
# your code
x=map(str,range(1,n+1))
y=' sheep...'
s=''
for i in x:
s+=i+y
return s
但是还可以想到使用自带的格式化字符串函数 str.format(),类似C里面的printf
其基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置,0,1对应format()括号中对象的顺序
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
也可以设置参数
print("名字:{name}, 得分 {score}".format(name="张三", score=12))
# 通过字典设置参数
dict = {"name": "张三", "score": 12}
print("姓名:{name}, 得分 {score}".format(**site))
# 通过列表索引设置参数
list = ['张三', 12]
print("姓名:{0[0]}, 得分 {0[1]}".format(list)) # "0" 是必须的,代表了format()括号中第一个元素
所以,答案可以写为
def count_sheep(n):
return "".join("{} sheep...".format(i) for i in range(1, n+1))