简体   繁体   English

Python 将数组转换为元素

[英]Python convert array to elements

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.我有一个示例数组['first_name', 'last_name']作为输入,并希望输出为“first_name”、“last_name”而不带任何方括号,但需要在元素周围加上双引号。 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)
array_list = ['first_name', 'last_name']
for i in array_list:
    print(f' "{i}" ',end=" ".join(","))
array_list = ['first_name', 'last_name']

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

Output:输出:

"first_name", "last_name"

You can add the intended quotation marks, you can do so with f-string您可以添加预期的引号,您可以使用 f-string

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

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您可以在下面尝试实现相同的效果。它具有循环遍历数组并将其转换为每个元素都带有双引号的字符串:@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)
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"

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

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"输出: "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.请记住:当您需要在字符串中放置双引号时,请用单引号括起来: ' " ' - 我故意留空。而" ' "则带有单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM