John Aiton
John Aiton

Reputation: 85

Join lines separated by a colon in Python

I want to re-format the text below using Python 3

text ="""alif
: the letter a [Sem ’-l-p (ox), Heb alef]
alifa
: be trusted, accustomed, tame 
alima
: feel pain 
"""

so that is outputs this way

alif : the letter a [Sem ’-l-p (ox), Heb alef]

alifa : be trusted, accustomed, tame

alima : feel pain

I tried using a solution to another problem, but can't figure out the regex

import re

print(re.sub('\n(:\n)','',text))

it just yielded the original text

Upvotes: 0

Views: 386

Answers (2)

Joshua Fox
Joshua Fox

Reputation: 19675

This will do it:

re.sub('\n:',':',text)

Your current code looks for a newline after the colon as well as before, but text has no such newlines.

Upvotes: 1

Himanshu Tripathi
Himanshu Tripathi

Reputation: 9

text ="""alif
: the letter a [Sem ’-l-p (ox), Heb alef]
alifa
: be trusted, accustomed, tame 
alima
: feel pain 
"""
print(text.replace('\n:',''))

output:
alif the letter a [Sem ’-l-p (ox), Heb alef]
alifa be trusted, accustomed, tame 
alima feel pain 

Upvotes: 1

Related Questions