Hi I would like to split some strings like these using python re module :
str1 = "-t Hello World -a New Developr -d A description"
str2 = "-t Bye -a sometext -d a large description"
I must keep the -
because I'm currently programming a python CLI project. I've tried using
re.split(r'(?=-)',aux)
but I recieved
['', '-t Hello World ', '-a Author ', '-d Description ']
instead of
['-t Hello World', '-a Author', '-d Description']
Any recommendation?
Try applying the strip() method on the results.
foo = re.split(r'(?=-)',str1)
foo = [s.strip() for s in foo]
Use a negative lookbehind to avoid splitting at the start of the string: (?<!^)
Then strip each of the resulting strings.
for s in str1, str2:
print([x.strip() for x in re.split(r'(?<!^)(?=\s+-)', str1)])
(I also added \s+
to avoid splitting words like Spider-Man
.)
Output:
['-t Hello World', '-a New Developr', '-d A description']
['-t Hello World', '-a New Developr', '-d A description']
However, I'd recommend looking into libraries that can do this for you - maybe argparse and shlex to start, and I would question where these strings are coming from, cause normally you deal with command line arguments as a list before parsing, like this:
['-t', 'Hello', 'World', '-a', 'New', 'Developr', '-d', 'A', 'description']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.