提问人:Bhargav 提问时间:2/13/2022 最后编辑:Bhargav 更新时间:2/16/2022 访问量:122
如何在屏幕上选择随机文本 [关闭]
How do I select random text on screen [closed]
问:
如何使用 Python 选择固定文本之后的随机文本?例如,“AWB NO 56454546”,其中“AWB NO”是固定文本,而“56454546”是随机文本。
答:
0赞
Jack Deeth
2/14/2022
#1
您可以使用该方法。它是内置类型的一部分。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.
如果用作分隔符,则将返回一个包含以下内容的 3 元组:"AWB No: "
- 之前的一切,例如
"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]
评论
0赞
Bhargav
2/14/2022
非常感谢您的详细回答先生,这意义重大:)
0赞
Jack Deeth
2/14/2022
不客气,我的朋友 - 祝你好运!
0赞
Bhargav
2/23/2022
嗨,先生,你能回答这个问题吗?“stackoverflow.com/q/71220374/18195529”很抱歉在这里发表评论,因为我没有任何其他方式可以联系您。
评论
_, _, awb_no = raw_text.partition("AWB NO ")
partition
是一个内置方法 - 您可以在任何字符串上使用它。试试看!print("correct horse battery staple".partition("horse"))