Amistad
Amistad

Reputation: 7400

Extracting parameters from a Python F-string

I have a python f-string as follows:

def send_string():
    ticket_id=123
    message = f'{ticket_id} Jira created successfully'
    return message

def extract_ticket_from_message(message):
    #pseudo code
    # Is it possible to extract the ticket id without parsing the 
    # whole string and using regex

Is there a convenient way of extracting the ticket_id value from the f-string without having to parse the whole string using regex in Python 3.6?

Upvotes: 2

Views: 1036

Answers (1)

Jongware
Jongware

Reputation: 22457

If

 ticket_id = 1234
 message = f'{ticket_id} Jira created successfully'

then – without using a regex –

def extract_ticket_from_message(message):
    return message.split()[0]

In other words, the first word. If ticket_id can be any string as well (so possibly containing spaces), you can still use this but cut off the final 3 words instead. (After all, you know what will follow.) If ticket_id is a more complex object that results in a string representation, there is no practical way to resolve it back to the original class/object/anything else than a Python primitive.

Noteworthy: you cannot get the original type without ambiguity. If the original was a string but its value was "1234", then you cannot know for sure if a string or number was passed.

Upvotes: 1

Related Questions