0

I'm attempting to programatically format a pdf menu, and all went well until I noticed certain line breaks out of place that break the pattern. This is what part of my raw text looks like:

LATIN
Saturday & Sunday: 
Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu
Scramble, Latin Roasted Vegetables
DESSERT
Daily: 
Assorted Pastries

I noticed that some items (like Latin Tofu Scramble) have a line break placed in the middle of them. Given that menu items are variable and there might be extra line breaks in other places, is there any way I can remove line breaks occurring between commas (since all of the items are comma-separated)?

EDIT: The final result would ideally look something like this:

LATIN
Saturday & Sunday: 
Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu Scramble, Latin Roasted Vegetables
DESSERT
Daily: 
Assorted Pastries
Mohammad Yusuf
  • 15,118
  • 9
  • 44
  • 71

2 Answers2

1

In python you can use the line.strip('\n') and line.strip('\t') to remove the newlines and tap spaces.

>>> line="Welcomes\n"
>>> line.strip("\n")
'Welcomes'

Or, you can use replace('\n','') to remove all the newline spaces from the String line.

>>> line="Welcomes\n"
>>> line.replace('\n','')
'Welcomes'
>>> 

Or, you can use rstrip() method to remove all the newline spaces from the String line

>>> line.rstrip()
'Welcomes'
K.Suthagar
  • 2,096
  • 1
  • 15
  • 28
1

try using re.sub with regex below with MULTILINE, it only replace line breaks that precedes with comma and next line containings comma

however, it won't works if the line break is at the last item, for eg. Latin Roasted Vegetables

txt = '''
LATIN
Saturday & Sunday: 
Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu
Scramble, Latin Roasted Vegetables
DESSERT
Daily: 
Assorted Pastries
'''

import re
newtxt = re.sub('(,[^\r\n]*?)[\r\n](?=[^\r\n]+?,)', r'\1 ', txt, re.MULTILINE)
# LATIN
# Saturday & Sunday:
# Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu Scramble, Latin Roasted Vegetables
# DESSERT
# Daily:
# Assorted Pastries
Skycc
  • 3,405
  • 1
  • 9
  • 17