So I've been curious to figure out how to do argument-parsing inside of input functions. For example:
a = input('enter something here: ')
now, lets say, if I input '--url example.com --data some_data_here' for example in a, how would I read the content after '--url' and '--data' separately? Help would be greatly appreciated :)
Here you go, in the below implementation the code is lengthy to be more descriptive and understandable, however once you understand the logic you can simplify it further.
Here I'm finding the index of url_identifier
and data_identifier
in the input_str
, adding their respective lengths to find the index where they end and 1 for space character and then I'm slicing the input_str
with the index data to get the required outputs.
def foo(input_str):
url_identifier = "--url"
data_identifier = "--data"
url_identifier_start_idx = input_str.find(url_identifier)
url_identifier_end_idx = url_identifier_start_idx + len(url_identifier) + 1
data_identifier_start_idx = input_str.find(data_identifier)
data_identifier_end_idx = data_identifier_start_idx + len(data_identifier) + 1
url = input_str[url_identifier_end_idx:data_identifier_start_idx]
data = input_str[data_identifier_end_idx:]
print(url)
print(data)
foo("--url google.com --data hello world")
OUTPUT
~/Rod-Cutting$ python hello.py
google.com
hello world