2024-06-25 23:56:00 发布
网友
再见
我对Python完全陌生,我正在尝试用string做一些事情。在
我想从给定字符串中删除双引号(")之间的\n字符,只删除:
"
\n
str = "foo,bar,\n\"hihi\",\"hi\nhi\""
所需输出必须是:
foo,bar "hihi", "hihi"
编辑:
所需的输出必须与该字符串类似: ^{cd4}
有什么提示吗?在
一个简单的有状态过滤器就可以做到这一点。在
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"'。关于这个问题。。。在
''
""
'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)
一个简单的有状态过滤器就可以做到这一点。在
这应该做到:
简要说明:Python字符串可以使用
''
或""
作为分隔符,因此通常的做法是在字符串中使用一个分隔符,以提高可读性。例如:'foo,bar,\n"hihi","hi\nhi"'
。关于这个问题。。。在您可能需要python regexp模块:re。 特别是,替换函数就是你想要的。有很多方法可以做到这一点,但是一个快速的选择是使用一个regexp来标识
""
子字符串,然后调用一个helper函数从这些子字符串中除去任何\n
。。。在相关问题 更多 >
编程相关推荐