Home > Back-end >  How do I select random text on screen
How do I select random text on screen

Time:02-15

How do I select the random text that is after a fixed text using Python? For Example "AWB NO 56454546" where "AWB NO" is fixed text while "56454546" is random text. enter image description here

CodePudding user response:

You can use the partition method for this. It's part of the built-in str type.

>>> help(str.partition)

partition(self, sep, /)
    Partition the string into three parts using the given separator.

    This will search for the separator in the string.  If the separator is found,
    returns a 3-tuple containing the part before the separator, the separator
    itself, and the part after it.

    If the separator is not found, returns a 3-tuple containing the original string
    and two empty strings.

If you use "AWB No: " as the separator, you'll get back a 3-tuple containing:

  • everything before "AWB No: " e.g. "Courier "
  • the separator: "AWB No: "
  • everything after "AWB No: ": "56454546"

So you can get that "everything after" part in two ways:

input_str = "Courier AWB No: 56454546"
sep = "AWB No: "
before, sep, after = input_str.partition(sep)
# == "Courier ", "AWB No: ", "56454546"

# or
after = input_str.partition(sep)[2]

# either way: after == "56454546"

If there are more words after the number you can get rid of them with .split()[0]:

input_str = "Courier AWB No: 56454546 correct horse battery staple"
sep = "AWB No: "
after = input_str.partition(sep)[2]
awb_no = after.split()[0]

# after == "56454546"

Or in one line:

input_str = "Courier AWB No: 56454546 correct horse battery staple"
awb_no = input_str.partition("AWB No: ")[2].split()[0]
  • Related