2

Given a list of floats:

my_list = [0.3, 0.11, -0.9]

I want a string literal object:

my_string = "0.3, 0.11, -0.9"

Attempt:

print(', '.join(inputs))
> TypeError: sequence item 0: expected str instance, float found
0

5 Answers 5

4

The compact way:

l = [0.3, 0.11, -0.9]

print (str(l)[1:-1])

Output:

0.3, 0.11, -0.9

Still, to be used with caution :). The "regular" way would be:

print (', '.join([str(x) for x in l]))
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

print(' , '.join(str(x) for x in [0.3, 0.11, -0.9]))

1 Comment

Updated your answer. Thanks :)
0

you can use join function of string like this:

first you have to convert float to str

my_string = ', '.join([str(i) for i in my_list])

2 Comments

There are many syntax issues with this answer. I tried my_string = ', '.join([float(i) for i in inputs]) but got TypeError: sequence item 0: expected str instance, float found.
you have to use str not float @ThePewCDestroyer
0

Arguably, the easiest way would be to do:

my_string = str(my_list)[1:-1]

This takes my_list, converts it into a string, and takes the characters from 1)leaving the first character at 0) to -1 (the end character is not taken)

1 Comment

Oh, interesting. Ty :)
0

A more pythonic way is to use map to first convert all the float values to str, and then use the function join to concatenate into a string.

print(', '.join(map(str, my_list)))

This prints 0.3, 0.11, -0.9 when my_list = [0.3, 0.11, -0.9]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.