首页 > 解决方案 > Python - While loop should return string

问题描述

Again I'm somewhat stuck with a task. This time my while loop should return a string of comma separated numbers. I do get the comma separated numbers out when I print them but the whole thing should be inside a string, and that's where I fail.

The code I use:

a = 7
b = ""

while a <= 20:
    b += (str(a) + ", ")
    a = a + 3

ANSWER = b          # Same result with str(b)

This produce: 7, 10, 13, 16, 19, and not "7, 10, 13, 16, 19," I don't think I should hard code it in... Any pointers on this?

Regards

标签: pythonstringwhile-loop

解决方案


如果您想要周围的引号,请尝试repr()

b = "7, 10, 13, 16, 19,"
print(repr(b))

输出(仅单引号,这依赖于str.repr(),您可以更改它):

'7, 10, 13, 16, 19,'

或者明确地将它们包装起来,或者将repr()'s 的输出更改为使用双引号:

print('"{}"'.format(b))
print('"{}"'.format(repr(b)[1:-1]))

输出:

"7, 10, 13, 16, 19,"

repr()给出一个包含 object 的可打印表示的字符串,对于大多数类型,结果repr()将适合eval()或放入您的源代码中.


推荐阅读