In my time-time value, I want to use a regular expression to strip out the slash and colon with time and replace it with an underscore

I am using Python, Webdriver for my automatic test. My script is on the admin page of our website. I click the "Add Project" button and I enter the name of the project.

Project Name I enter the format LADEMO_IE_05/20/1515:11:38 This is the date and time at the end.

What I would like to do is use the regex that I would like to find in / and: and replace them with an underscore _

I developed a regex expression:

[0-9]{2}[/][0-9]{2}[/][0-9]{4}:[0-9]{2}[:][0-9]{2}

This finds 2 digits, then /followed by 2 digits, then /etc.

I would like to replace /and :on _.

Can I do this in Python using import? I need help with the syntax.

My method that returns the date:

def get_datetime_now(self):
            dateTime_now = datetime.datetime.now().strftime("%x%X")
            print dateTime_now #prints e.g. 05/20/1515:11:38
            return dateTime_now

My code snippet for entering the project name in the text box:

project_name_textfield.send_keys('LADEMO_IE_' + self.get_datetime_now())

The output is, for example,

LADEMO_IE_05/20/1515:11:38

I would like Output to be:

LADEMO_IE_05_20_1515_11_38 
+4
source share
4 answers

Just format the date and time using the strftime()in the desired format :

>>> datetime.datetime.now().strftime("%m_%d_%y%H_%M_%S")
'05_20_1517_20_16'
+9
source

Another simple option is to simply replace the line:

s = "your time string"
s = s.replace("/", "_").replace(":", "_")
+6
source

:

i) strftime :

strftime("%m_%d_%y_%H_%M_%S")

ii) replace() , '/' ':' '_'

+1

Basically, you want a ton to replace every invalid character with an underscore. To do this, instead of using a regular expression, you can simply use the method str.replace. For instance:

out_string = in_string.replace('/', '_').replace(':', '_')

In this example, the first substitution returns a string with a slash replacement, and the second call replaces the colons. I think this is the easiest way to replace one or two characters. But, if you want your program to grow, I advise you to use it re.subas follows:

# first we compile the regex, for speed sake
# this regex match every one of the bad characters, and it modular: just add one, in case
bad_characters = re.compile(r'/|:')

# your code

# replacement
out_string = re.sub(bad_characters, '_', in_string)
+1
source

Source: https://habr.com/ru/post/1589019/


All Articles