Reputation: 69
I need to convert a group of variables (result sets from BeautifulSoup) into strings. Is there an elegant way to do this to all of them at once instead of one by one? I was thinking something like this -
for name in [company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax]:
name = str(name)
I would also like to do a similar thing with re.sub -
for name in [company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax]:
re.sub('<[^<]+?>', '', name)
Thanks
Upvotes: 0
Views: 51
Reputation: 43314
for name in [company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax]:
name = str(name)
This will not work because you are modifying the list inside the for loop, you can however use a list comprehension for this, which is a one-liner:
list_as_strings = [str(name) for name in [company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax]]
Demo
>>> a = [1, 2, 3, 4]
>>> for i in a:
... i = str(i)
...
>>> a
[1, 2, 3, 4]
>>> b = [str(i) for i in a]
>>> b
['1', '2', '3', '4']
Upvotes: 1
Reputation: 142651
List comprehension should be faster but this solution can be more readable for you.
list1 = [company_name, company_address, company_logo]
list2 = []
for name in list1:
list2.append( str(name) )
company_name, company_address, company_logo = list2
Now you have strings in previous variables.
Upvotes: 0