首页 > 解决方案 > 试图用固定在点的“_”反转字符串

问题描述

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

我尝试使用上面的代码来转换以下字符串

输入: ab_cde

预期输出: ed_cba

标签: pythonstring

解决方案


s = 'ab_cde'

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

print(out)

印刷:

ed_cba

编辑:更多固定点:

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

推荐阅读