Home > Software engineering >  python array to string but with commas on every string return
python array to string but with commas on every string return

Time:02-15

I have a array something like this

my_array = ['MY_INVOICE', 'YOUR_INVOICE']

and when I convert it to a string using like this

final_string  =  ','.join(my_array)

it is giving something like this

MY_INVOICE,YOUR_INVOICE

while I want something like this

"MY_INVOICE", "YOUR_INVOICE" (like with commas on it) tried few solutions but not working

CodePudding user response:

Here's what I think you're looking for.

my_array = ['MY_INVOICE', 'YOUR_INVOICE']
print('"'   '", "'.join(my_array)   '"')

Result:

"MY_INVOICE", "YOUR_INVOICE"

CodePudding user response:

May be :

final_string  =  '"'   '", "'.join(my_array)   '"'

CodePudding user response:

You could do something like this:

my_array = ['MY_INVOICE', 'YOUR_INVOICE']
my_array[0] = '"'   my_array[0] # Adding opening double quotes to the first value
my_array[-1] = my_array[-1]   '"' # Adding closing double quotes to the last value
print('", "'.join(my_array)) # Joining with quotes and comma with space

CodePudding user response:

To turn this list…

my_array = ['MY_INVOICE', 'YOUR_INVOICE']

…into this string:

"MY_INVOICE", "YOUR_INVOICE"

You could do this:

new_str = ', '.join(f'"{word}"' for word in my_array)
Explanation:

f'"{word}"' takes word and puts double-quotes around it - if word was Apple it becomes "Apple"

f'"{word}"' for word in my_array does this for each word in my_array

', '.join(...) joins together the pieces with , in between

CodePudding user response:

I solved your problem by trying to change your code as less as possible. This is my solution which works fine, even though I don't really know why you would do something like this. Anyway that's not my problem.

my_array = ['MY_INVOICE', 'YOUR_INVOICE']
my_array = (f"\"{element}\"" for element in my_array)
final_string = ""
final_string  =  ','.join(my_array)

This is the output:

"MY_INVOICE","YOUR_INVOICE"

CodePudding user response:

Try:


my_array = ['MY_INVOICE', 'YOUR_INVOICE']

final_string = ''

final_string  =  '\"'  '\", \"'.join(my_array)   '\"'

print(final_string)


wich outputs: "MY_INVOICE", "YOUR_INVOICE"

CodePudding user response:

while I want something like this

"MY_INVOICE", "YOUR_INVOICE" (like with commas on it)

I think you mean quotes ("), not commas (,) which your original version already has.

You need to add the quotes yourself. One way is with a generator expression:

final_string  =  ', '.join('"'   w   '"' for w in my_array)

Here I add the quotes around each word before joining them together with commas.

  • Related