py3 - 在所有级别的字符串中反转标记的子字符串
py3 - reverse marked substrings within strings on all levels
我正在尝试反转字符串中括号中的所有子字符串。这个 post () 向我展示了如何做到这一点(我正在使用第一个答案),但是我在括号内的括号中遇到了问题。该代码目前不适用于多层括号。例如字符串 'ford (p(re)fe)ct',应该 return 为 'ford efrepct',但 return 为 'ford er(pfe)ct'。 (它应该反转每个括号相对于其父元素的内容)。
这是我的代码:
def reverseInParentheses(iss):
import re
new = re.sub('\((.*?)\)', lambda m: m.group(1)[::-1], iss)
print(new)
谢谢!
解决此问题的一种简单而幼稚的方法:排除匹配组中的左括号,然后重复直到没有更多括号。
import re
def reverseInParentheses(iss):
while '(' in iss:
iss = re.sub('\(([^\(]*?)\)', lambda m: m.group(1)[::-1], iss)
return iss
print(reverseInParentheses('ford (p(re)fe)ct'))
# ford efrepct
这是我不使用正则表达式的解决方案。也许它可以通过使用列表推导甚至使用递归来写得更紧凑 - 但我认为这已经够奇怪了 ;)
def reverse_in_parenthesis(str0):
separators = ['(', ')']
for separator in separators:
if not separator in str0:
return str0
str1 = str0.split('(') # ['ford ', 'p', 're)fe)ct']
str2 = str1[-1].split(')') # ['re', 'fe', 'ct']
res = str1[0] # everything before 1st '(' remains as is
for i,s in enumerate(str2[:-1][::-1]):
res = ''.join((res, s if i%2 else s[::-1]))
for i,s in enumerate(str1[1:-1][::-1]):
res = ''.join((res, s if i%2 else s[::-1]))
res = ''.join((res, str2[-1])) # everything after last ')' remains as is
return res
print(reverse_in_parenthesis('ford (p(re)fe)ct'))
输出:
ford efrepct
我正在尝试反转字符串中括号中的所有子字符串。这个 post (
这是我的代码:
def reverseInParentheses(iss):
import re
new = re.sub('\((.*?)\)', lambda m: m.group(1)[::-1], iss)
print(new)
谢谢!
解决此问题的一种简单而幼稚的方法:排除匹配组中的左括号,然后重复直到没有更多括号。
import re
def reverseInParentheses(iss):
while '(' in iss:
iss = re.sub('\(([^\(]*?)\)', lambda m: m.group(1)[::-1], iss)
return iss
print(reverseInParentheses('ford (p(re)fe)ct'))
# ford efrepct
这是我不使用正则表达式的解决方案。也许它可以通过使用列表推导甚至使用递归来写得更紧凑 - 但我认为这已经够奇怪了 ;)
def reverse_in_parenthesis(str0):
separators = ['(', ')']
for separator in separators:
if not separator in str0:
return str0
str1 = str0.split('(') # ['ford ', 'p', 're)fe)ct']
str2 = str1[-1].split(')') # ['re', 'fe', 'ct']
res = str1[0] # everything before 1st '(' remains as is
for i,s in enumerate(str2[:-1][::-1]):
res = ''.join((res, s if i%2 else s[::-1]))
for i,s in enumerate(str1[1:-1][::-1]):
res = ''.join((res, s if i%2 else s[::-1]))
res = ''.join((res, str2[-1])) # everything after last ')' remains as is
return res
print(reverse_in_parenthesis('ford (p(re)fe)ct'))
输出:
ford efrepct