What is the pythoninc way to replace multiple new line with single and single new line with one space?
Create a mapping dictionary:
dct = {'\n\n': '\n', '\n': ' '}
Using re.sub
(The order of this regex is important):
re.sub(r'(\n\n|\n)', lambda x: dct[x.group()], s)
Output:
'2 Our strategy drives sustainably higher profits and margins\nStrengthening our hubs is a critical foundation to maximize profitability\nDriving revenue improvements from all areas of business\nImproving efficiency and productivity \nGreater accountability and transparency '
A bit of explanation to how this works. Python's regular expression module does not support overlapping matches, so when it matches \n\n
, it will not also match \n
, which allows you to do both replacements in a single step.
How to set the current working directory?
Try os.chdir
os.chdir(path)
Change the current working directory to path. Availability: Unix, Windows.
How to increment datetime by custom months in python without using library
Edit - based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:
import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month // 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year,month)[1])
return datetime.date(year, month, day)
In use:
>>> somedate = datetime.date.today()
>>> somedate
datetime.date(2010, 11, 9)
>>> add_months(somedate,1)
datetime.date(2010, 12, 9)
>>> add_months(somedate,23)
datetime.date(2012, 10, 9)
>>> otherdate = datetime.date(2010,10,31)
>>> add_months(otherdate,1)
datetime.date(2010, 11, 30)
Also, if you're not worried about hours, minutes and seconds you could use date
rather than datetime
. If you are worried about hours, minutes and seconds you need to modify my code to use datetime
and copy hours, minutes and seconds from the source to the result.
Related Topics
Discord.Py | Add Role to Someone
How to Match a Newline Character in a Raw String
Iterating Over Every Two Elements in a List
Formal and Actual Parameters in a Function in Python
Python | Count Number of False Statements in 3 Rows
Run Multiple Python File Concurrently
Python - Outputting Variables to Txt File
Converting Exponential to Float
Plot Two Histograms on Single Chart With Matplotlib
How to Get the Name of an Object
How to Convert Signed to Unsigned Integer in Python
How to Iterate Through Cur.Fetchall() in Python
Python-Compare Two String Columns in Same Dataframe, Return Matching Result
Converting a Numpy Array into a Dict of Values Mapped to Rows
Importing Zip File in Google Colaboratory Stored in Google Drive
Find the Longest Substring in Alphabetical Order
How to Rotate Xticks on One Axis of Figure in Matplotlib Without "Getting" the Labels as a List