Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I separate a part of an input and convert it into a variable?

I’m working on a simple program and I was wondering how can I separate a part of the input and turn that separated part into a variable.

For example: START {chrome.exe}.

Basically I want to take that string in between those curly brackets and turn it into a variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks,

>Solution :

For this kind of operation, it is a good idea to use regular expressions.
Python has a builtin module for using regexes, called re. You can use its findall function to find all the strings which match a certain pattern, and then simply get the first item in the resulting list (which will only have one item anyway).


Here is what the code would look like:

import re

inp = input()
var = re.findall(r"{(.*?)}", inp)

print(var)

Given an input of:

START {chrome.exe}

This outputs:

chrome.exe

Here is an explanation of how the regex works:

  • The { and } characters match the literal characters { and }
  • The ( and ) characters are special characters which group together tokens
  • The . character is a special character which matches any character except newlines
  • The * character is a special character which means that the last token can match any number of itself (not just 1). This means that the . will now match a run of multiple non-newline characters, not just one character
  • The ? character is a special character which alters the meaning of the preceding *. Now, instead of matching as many characters as possible ("greedy"), which would cause the .* to continue after the } and match the whole rest of the string, the .*? matches as few characters as possible ("lazy"), so it only matches up to the next } character
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading