Python将三个双引号和四个双引号替换为双引号。

huangapple go评论65阅读模式
英文:

Python-replace tripple and 4 times double quotes with a double quote

问题

I have a String like this:

"""{\""College\""

Want to remove 3 and 2 times double quotes to only one time like this:

"{\"College\"

How can I do that, I tried the replace() function but it removes all the quotes. Can someone help please, I am new to Python?

Tried replace("\"\"","\""), but not working.

英文:

I have String like this:

"""{\""College\""

Want to remove 3 and 2 times double quotes to only one time like this:

"{\"College\"

How can I do that , I tried replace() function but it removes all the quotes.Can someone help please I am new to Python

Tried replace("\"\"","\"") but not working

答案1

得分: 1

1

以下代码重复替换 2 个 " 为 1 个 "。
它执行 log(n) 次循环,不像单个循环那样高效,但可读性较好,算法明显。

mystring = '"""{\""College\""''
while '""' in mystring:
    mystring = mystring.replace('""', '"')
print(mystring)

(timeit 显示每次循环 430 纳秒)

2

另一种更复杂且更高效(适用于更大字符串)的一行代码:

print('"'.join((e for e in ('|'+mystring+'|').split('"') if e))[1:-1])

(timeit 显示每次循环 945 纳秒)

' | ' 用于填充字符串,以考虑边缘情况,即字符串两端有 "。

3

最后,基于正则表达式的解决方案(在Python中有时速度较慢)

import re
print(re.sub('"+', '"', mystring))

(timeit 显示每次循环 1.28 微秒)

英文:

1

the following code repeatedly replaces 2 " with 1 ".
It does do log(n) loops and is not as efficient as a single loop would be, but it is readable and the algorithm is obvious.

mystring = '"""{\""College\""'
while '""' in mystring:
    mystring = mystring.replace('""', '"')
print(mystring)

(timeit shows 430 ns per loop)

2

alternate more complicated + more efficient(for larger strings) oneliner:

print('"'.join((e for e in ('|'+mystring+'|').split('"') if e))[1:-1])

(timeit shows 945 ns per loop)

the '|' is used to pad the string to account for the edge case where there are " on the ends.

3

and finally a regex based solution (sometimes pretty slow in python)

import re
print(re.sub('"+', '"', mystring))

(timeit shows 1.28 µs per loop)

答案2

得分: 0

你可以用一个简单的正则表达式来解决这个问题。例如,表达式 \"{2,3} 可以匹配任何双引号或三引号。

英文:

You could solve this with a simple regular expression (Docs).

For instance the expression: \"{2,3} would match any double or triple quotes.

huangapple
  • 本文由 发表于 2023年2月19日 01:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定