Reputation: 421
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
Upvotes: 0
Views: 1453
Reputation: 1725
Try:
my_array = ['MY_INVOICE', 'YOUR_INVOICE']
final_string = ''
final_string += '\"' +'\", \"'.join(my_array) + '\"'
print(final_string)
wich outputs: "MY_INVOICE", "YOUR_INVOICE"
Upvotes: 0
Reputation: 390
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"
Upvotes: 0
Reputation: 3357
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)
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
Upvotes: 0
Reputation: 83537
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.
Upvotes: -1
Reputation: 4772
Here's what I think you're looking for.
my_array = ['MY_INVOICE', 'YOUR_INVOICE']
print('"' + '", "'.join(my_array) + '"')
Result:
"MY_INVOICE", "YOUR_INVOICE"
Upvotes: 2
Reputation: 1362
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
Upvotes: 0