如何从字符串中删除\n双引号之间的found?

2024-06-25 23:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

再见

我对Python完全陌生,我正在尝试用string做一些事情。在

我想从给定字符串中删除双引号("之间的\n字符,只删除

str = "foo,bar,\n\"hihi\",\"hi\nhi\""

所需输出必须是:

foo,bar
"hihi", "hihi"

编辑:

所需的输出必须与该字符串类似: ^{cd4}

有什么提示吗?在


Tags: 字符串编辑stringfoobarhi字符事情
3条回答

一个简单的有状态过滤器就可以做到这一点。在

in_string  = False
input_str  = 'foo,bar,\n"hihi","hi\nhi"'
output_str = ''

for ch in input_str:
    if ch == '"': in_string = not in_string
    if ch == '\n' and in_string: continue
    output_str += ch

print output_str

这应该做到:

def removenewlines(s):
    inquotes = False
    result = []

    for chunk in s.split("\""):
        if inquotes: chunk.replace("\n", "")
        result.append(chunk)
        inquotes = not inquotes

    return "\"".join(result)

简要说明:Python字符串可以使用''""作为分隔符,因此通常的做法是在字符串中使用一个分隔符,以提高可读性。例如:'foo,bar,\n"hihi","hi\nhi"'。关于这个问题。。。在

您可能需要python regexp模块:re。 特别是,替换函数就是你想要的。有很多方法可以做到这一点,但是一个快速的选择是使用一个regexp来标识""子字符串,然后调用一个helper函数从这些子字符串中除去任何\n。。。在

import re
def helper(match):
    return match.group().replace("\n","")
input = 'foo,bar,\n"hihi","hi\nhi"'
result = re.sub('(".*?")', helper, input, flags=re.S)

相关问题 更多 >