Python 尝试用“倒”来反转字符串_&引用;定点

Python 尝试用“倒”来反转字符串_&引用;定点,python,string,Python,String,我尝试使用上述代码转换以下字符串 输入:ab\u cde 预期输出:ed\u cba def r(s): str = [] for i in len(s): if (s[i]=='_'): str = s[i] + str continue str = s[i] + str return str 印刷品: s = 'ab_cde' out = '' for a, b in zip(s, s[::-1]): if b != '_' an

我尝试使用上述代码转换以下字符串

输入:
ab\u cde

预期输出:
ed\u cba

def r(s): 
  str = []
  for i in len(s):
   if (s[i]=='_'): 
    str = s[i] + str
    continue   
   str = s[i] + str
  return str
印刷品:

s = 'ab_cde'

out = ''
for a, b in zip(s, s[::-1]):
    if b != '_' and a != '_':
        out += b
    else:
        out += a

print(out)
s = 'ab_cde_f_ghijk_l'

i, out = iter(ch for ch in s[::-1] if ch != '_'), ''

out = ''.join(ch if ch == '_' else next(i) for ch in s)
print(out)

编辑:有关更多固定点:

ed_cba
印刷品:

s = 'ab_cde'

out = ''
for a, b in zip(s, s[::-1]):
    if b != '_' and a != '_':
        out += b
    else:
        out += a

print(out)
s = 'ab_cde_f_ghijk_l'

i, out = iter(ch for ch in s[::-1] if ch != '_'), ''

out = ''.join(ch if ch == '_' else next(i) for ch in s)
print(out)

其主要思想是检查下划线的所有位置,保存它们并反转没有它们的字符串,在反转后再次插入它们

lk_jih_g_fedcb_a
该函数可以修改为具有不同的固定字符

我还使用regex函数的包
re
来识别
,如果您愿意,您可以使用一个简单的循环,如
下划线\u位置=[I代表I,c在枚举中,如果c=''']

import re

def r(s):
  # check where all the underscore are
  underscore_positions = [m.start() for m in re.finditer('_', s)]
  # get list of reversed chars without underscores
  reversed_chars = [c for c in reversed(s) if c != '_']
  # put underscore back where they where
  for p in underscore_positions:
    reversed_chars.insert(p, '_')
  # profit
  return "".join(reversed_chars)
这项工作由以下人员完成:

  • 存储定点字符的位置
  • 在删除
    字符的情况下反转字符串
  • “\uquot
    插回正确的位置

  • 这似乎不适用于具有多个固定点的字符串,例如,
    “ab\u cde\u f\u ghijk\u l”
    @MateenUlhaq更新了我的答案。虽然这段代码可能解决了这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。