簡體   English   中英

在Python中刪除特定的換行符

[英]Removing specific line breaks in Python

我試圖以編程方式設置pdf菜單的格式,但一切進行得很好,直到我注意到某些換行符中斷了模式。 這是我的原始文本的一部分:

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

我注意到某些項目(例如拉丁豆腐爭奪戰)中間有一個換行符。 鑒於菜單項是可變的,並且在其他地方可能會有額外的換行符,我有什么辦法可以消除逗號之間出現的換行符(因為所有項目都以逗號分隔)?

編輯 :理想的最終結果是這樣的:

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

在python中,您可以使用line.strip('\\n')line.strip('\\t')刪除換行符並點擊空格。

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

或者,您可以使用replace('\\ n','')從String行中刪除所有換行符。

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

或者,您可以使用rstrip()方法從字符串行中刪除所有換行符空間

>>> line.rstrip()
'Welcomes'

嘗試在MULTILINE下將re.sub與正則表達式一起使用MULTILINE ,它僅替換以逗號MULTILINE換行符和包含逗號的下一行

但是,如果換行符位於最后一個項目上,則無法使用,例如 拉丁烤蔬菜

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM