What Is the Pythoninc Way to Replace Multiple New Line With Single and Single New Line With One Space

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



Leave a reply



Submit