Home > database >  How to convert python list into a string after manipulating?
How to convert python list into a string after manipulating?

Time:03-01

I have a python list...

my_list = [1, 2, 3, 4, 5, 6]

Can anyone tell me please how can I convert this list into a string after manipulating.

Expectation...

my_string = "mx_hh|1&mx_hh|2&mx_hh|3&mx_hh|4&mx_hh|5&mx_hh|6"

CodePudding user response:

You could use a combination of string concatenation and str.join:

>>> print("mx_hh|"   "&mx_hh|".join(str(i) for i in my_list))
"mx_hh|1&mx_hh|2&mx_hh|3&mx_hh|4&mx_hh|5&mx_hh|6"

Notice the transformation of the elements in my_list to str to be able to use str.join

CodePudding user response:

Note that your task can be decomposed into two steps: first step is to convert the integers into a strings, like 1 into mx_hh|1. Then you join those with '&'.

You can combine join with list (or generator) comprehension:

my_list = [1, 2, 3, 4, 5, 6]

my_string = '&'.join(f"mx_hh|{x}" for x in my_list)
print(my_string) # mx_hh|1&mx_hh|2&mx_hh|3&mx_hh|4&mx_hh|5&mx_hh|6

CodePudding user response:

One approach is this:

  • use a Python f-string to format each element in my_list according to your requirement, namely with the "mx_hh|" prefix
  • iterate over the elements in my_list using Python comprehension syntax: do_something() for v in my_list
  • concatenate each of these formatted strings with the connecting character "&" according to your requirement, using the join() method of the str datatype
  • assign the result to my_string
my_string = '&'.join(f'mx_hh|{v}' for v in my_list)
print(my_string)

Output is:

mx_hh|1&mx_hh|2&mx_hh|3&mx_hh|4&mx_hh|5&mx_hh|6
  • Related