简体   繁体   English

出现“ \\ r \\ n”时,用逗号分隔字符串

[英]Separation the string with comma when occurs “\r\n”

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. 我有一个字符串,其中有“ \\ r \\ n”,想要在其中删除并插入逗号,并在数组中有几个元素。

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'> my_list是: <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. 那是因为您使用的return将在for循环的第一次迭代之后返回,因此您可以将return更改为yield ,这将为您提供一个可以迭代的生成器。

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(",") 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. 您只会得到一个字符串,因为您正在执行for循环内的return而不是after。 And instead of doing .append inside the for loop you can do this with a list comprehension. 而且,除了在for循环中添加.append ,您还可以使用列表理解功能。 Assuming your test_method otherwise works as intended it would look like this: 假设您的test_method可以按预期工作,则它看起来像这样:

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: 但是,如果你想要做的唯一的事情就是更换\\r\\n,你的字符串中,最后一排可以简化成这样:

return [i.replace('\r\n', ',') for i in my_list]

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

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