0

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

2 Answers 2

1
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']
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't change the object type. Result of print (type(company_name)) <class 'bs4.element.ResultSet'>
@metalayer you cannot change an object's type. You can however reassign the new values to the existing variables: company_name, company_address, company_logo, company_cat, company_lat, company_phone, company_fax = list_as_strings, that will get the result that you want
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.