Python - While loop should return string

3363 views python
2

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

answered question

That is a string, print won't show the quotes.

Note - you can do this using: print(*range(7, 20, 3), sep=', ') if you only really want to print it - but I imagine you're supposed to be using range if possible here

3 Answers

3

This is actually a String. You can test this by printing the value of type:

>>> print(type(b))  
<class 'str'>

posted this
12

If you want the surrounding quotes, try repr():

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

Output (single quotes only, this relies on str.repr(), you can change it):

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

Or explicitly wrap them up or change repr()'s output to use double quotes:

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

Output:

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

repr() gives a string containing a printable representation of an object, and for most types, the result of repr() would be suitable for eval(), or to be put in your source code.

posted this
0

a = 7
b = ""

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

ANSWER = f'"{b}"'
print(ANSWER)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 letters_dict.py 
"7, 10, 13, 16, 19, "

posted this

Have an answer?

JD

Please login first before posting an answer.