I have a string in which there are "\\r\\n", wants to remove and insert a comma there and have a couple of elements in the array.
This is my code:
def test_method(self):
my_list = self.texts.filter(code='open')
for i in my_list:
return strip_tags(i.text.replace('\r\n', ',').split(','))
my_list is: <class 'django.db.models.query.QuerySet'>
I only have one string with commas.
I assume the error you're having is that it is only working for the one line.
That is because you're using return
which will return after the first iteration of your for loop, so you can change return
to yield
and this will provide you a generator you can iterate over.
for i in my_list:
yield strip_tags(i.text.replace('\r\n', ',').split(','))
Otherwise, if its a list you want to end up with. You need to make a temporary list first
ret_val = []
for i in my_list:
ret_val.append(strip_tags(i.text.replace('\r\n', ',').split(',')))
return ret_val
As you require array of elements as final outcome, you can create an array from comma separated string
couple_of_elements_comma_separated_string.split(",")
What are you exactly looking for? Something else?
You only get one string because you're doing return
inside the for loop instead of after. And instead of doing .append
inside the for loop you can do this with a list comprehension. Assuming your test_method
otherwise works as intended it would look like this:
def test_method(self):
my_list = self.texts.filter(code='open')
return [strip_tags(i.text.replace('\r\n', ',').split(',')) for i in my_list]
However, if the only thing you want to do is to replace \\r\\n
with ,
within your strings, the last row could be simplified to this:
return [i.replace('\r\n', ',') for i in my_list]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.