user2261062
user2261062

Reputation:

Joining different list data types into string

I need to join the elements of a list into a string (looks simple so far).

However this list has some elements that are strings and others that are numbers.

What I want to achieve is a string where the original strings are still quoted but the numbers are not:

Example:

mystring = ['text field', 24, 'text2', 55.45]

Expected output (this is actually a string, I removed the opening and closing quotes for clarity, the simple quotes must be part of the string!):

'text field', 24, 'text2', 55.45

What I tried so far:

>>> ', '.join(mystring)

then the interpreter complains about the int:

TypeError: sequence item 1: expected string, int found

If I try to map everything to string, then I miss the quotes for string.

>>> ', '.join(map(str,a))

'text field, 24, text2, 55.45'

Of course I could modify my original list to look like:

mylist2 = ["'text field'", 24, "'text2'", 55.45]

and then it works but I really want to keep my original list and achieve the desired result.

Any suggestions?

Upvotes: 2

Views: 501

Answers (4)

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

Can't you just take the string representation of the list and cut off the brackets? Sounds like that's what you're actually trying to achieve anyway.

>>> str(mystring)[1:-1]
"'text field', 24, 'text2', 55.45"

Upvotes: 1

ettanany
ettanany

Reputation: 19816

An approach would be:

', '.join("'{}'".format(s) if isinstance(s, str) else str(s) for s in mystring)

Output:

>>> mystring = ['text field', 24, 'text2', 55.45]
>>> 
>>> ', '.join("'{}'".format(s) if isinstance(s, str) else str(s) for s in mystring)
"'text field', 24, 'text2', 55.45"

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

Simply convert the elements in the .join to a string by using the str(..) builtin:

', '.join(str(x) for x in mystring)

If you want however to add quotation marks around your strings, you should use repr(..):

', '.join(repr(x) for x in mystring)

Example in the interactive shell:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str('aa')
'aa'
>>> mystring = ['text field', 24, 'text2', 55.45]
>>> ', '.join(str(x) for x in mystring)
'text field, 24, text2, 55.45'
>>> ', '.join(repr(x) for x in mystring)
"'text field', 24, 'text2', 55.45"

Note that the double quotes (") are not part of the actually string, they are there to show we are talking about a string.

Upvotes: 3

Daniel
Daniel

Reputation: 42768

Use repr:

>>> mystring = ['text field', 24, 'text2', 55.45]
>>> ', '.join(map(repr, mystring))
"'text field', 24, 'text2', 55.45"

Upvotes: 4

Related Questions