2

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?

8
  • 2
    Well, the variable ticket_id should hold it. I'm guessing that's not what you're looking for... can you expand a bit? Maybe with a little more example code? Commented Nov 15, 2018 at 18:23
  • is "ticket_id" literally the expected output in your example, or are you expecting a ticket id like "1234"? Does the solution need to be generalized? Do we have any garauntees about what ticket_id is going to be: i.e.- do we know it won't contain spaces and you can simply use message.split(maxsplit=1)[0]? Commented Nov 15, 2018 at 18:23
  • Why not simply yourDesiredResult = str(ticket_id)? Is this an XY problem? Commented Nov 15, 2018 at 18:26
  • @usr2564301, Why not yourDesiredResult = ticket_id? Commented Nov 15, 2018 at 18:28
  • @Austin: in the formatted f-string it will be a string. It looks like OP is thinking about alternatives to getting its value as a string. We will have to await clarification, though. Commented Nov 15, 2018 at 18:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.