python - 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
解决方案
如果您想要周围的引号,请尝试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()
或放入您的源代码中.
推荐阅读
- c# - 如何修复 NuGet 包 Razor 运行时编译错误?
- xamarin - Xamarin Forms中android上的圆形复选框
- python - 在python中使用自定义函数
- c# - CollectionProperties 上的过滤器给了我所有 4 条记录而不是 2 条
- php - 使用 DataTables 在 Laravel 中按雄辩的关系排序
- laravel - Laravel 中 i18n t() 函数的等效函数是什么?
- javascript - Cloud Firestore 找不到自定义文档 ID
- azure - 如何更改 Azure DevOps 工作项中工作项的日期格式
- nginx - 为什么 Safari 在重定向时发送 Origin 标头?
- python - 如何使用装饰器来引入函数和参数?