Home > OS >  Python convert array to elements
Python convert array to elements

Time:12-16

I have a sample array ['first_name', 'last_name'] as input and would like to have the output as "first_name", "last_name" without any square brackets but need to have the double quotes around the elements. I have tried below but doesn't seem to work. appreciate any inputs on this.

The array is dynamic. Can have any number of elements. The elements need to be enclosed in double quotes each and no square brackets.

      array_list = ['first_name', 'last_name']
      string_list = list(array_list)
      print(string_list)

CodePudding user response:

array_list = ['first_name', 'last_name']
for i in array_list:
    print(f' "{i}" ',end=" ".join(","))

CodePudding user response:

You can add the intended quotation marks, you can do so with f-string

string_list = [f'"{item}"' for item in array_list]
print(", ".join(string_list))

CodePudding user response:

you can try below to achieve the same.It has for loop to iterate through the array and convert it to a string with double quotes around each element: @Pal1989

array_list = ['first_name', 'last_name']
string_list = ""
for element in array_list:
  string_list  = '"'   element   '", '
string_list = string_list[:-2]
print(string_list)

CodePudding user response:

array_list = ['first_name', 'last_name']

print(', '.join(f'"{e}"' for e in array_list))

Output:

"first_name", "last_name"

CodePudding user response:

array_list = ['first_name', 'last_name']
pre_processed = [f'"{item}"' for item in array_list]
string_list = ", ".join(pre_processed)
print(string_list)

Output:

"first_name", "last_name"

CodePudding user response:

you can do like this using list-string conversion...

Code

array_list = str(['first_name', 'last_name',5]).strip('[]')
print(array_list)
#-------OR--------
array_list = ['first_name', 'last_name'] # only string handle 
print(",".join(array_list))

output

'first_name', 'last_name', 5

CodePudding user response:

All you really need to do is to join by the separator and put double quotes at front and back:

array_list = ['first_name', 'last_name']
print('"'   '", "'.join(array_list)   '"')
output: "first_name", "last_name"

Remember: when you need to put double quotes in strings, surround with singles: ' " ' - I've left blanks on purpose. And " ' " to have single quotes.

  • Related