如何使用Python选择固定文本之后的随机文本?例如";AWB编号56454546";其中";AWB NO";是固定文本,而";56454546";是随机文本。
您可以为此使用partition
方法。它是内置str
类型的一部分。
>>> 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.
如果您使用"AWB No: "
作为分隔符,您将返回一个包含以下内容的3元组:
"AWB No: "
之前的所有内容,例如"Courier "
- 分隔符:
"AWB No: "
"AWB No: "
:"56454546"
之后的所有内容
所以你可以得到";在";以两种方式组成:
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"
如果数字后面有更多的单词,你可以用.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"
或者在一行中:
input_str = "Courier AWB No: 56454546 correct horse battery staple"
awb_no = input_str.partition("AWB No: ")[2].split()[0]