我试图用一个字符串替换一堆\ n,用空格和' //',而不是字符串中的ALL \ n。
幸运的是,我有一个模式:每隔四分之一
示例:
\n jack ryan
\n policeman and pony enthusiast
\n german
\n john anderson <--- don't remove this \n
\n fisherman
\n swedish
\n barack putin <--- don't remove this \n
\n french
\n programmer
输出:
jack ryan // policeman and pony enthusiast // german
john // fisherman // swedish
barack // french // programmer
我找了一个简单的注册解决方案,但我找不到我需要的东西。
我希望有人可以提供帮助!
答案 0 :(得分:4)
您的输入对我来说看起来有点滑稽,但这可以实现您的要求:
input = '\n jack ryan \n policeman and pony enthusiast \n german \n john anderson \n fisherman \n swedish \n barack putin \n french \n programmer'
# Split on '\n':
lines = input.splitlines()
# Remove the first empty line:
lines = lines[1:]
output = ''
step_size = 3
for i in range(0, len(lines), step_size):
output += '//'.join(lines[i:i + step_size]) + '\n'
print output
输出:
jack ryan // policeman and pony enthusiast // german
john anderson // fisherman // swedish
barack putin // french // programmer
答案 1 :(得分:1)
您可以通过捕获组后跟换行符来使用正则表达式执行此操作:
import re
re.sub(r"([^\n]+)\n([^\n]+)\n([^\n]+)(\n?)", r"\1 // \2 // \3\4", s)