如何提取这个字符串的id?

How to extract the id of this string?


对于其他字符串,它工作正常,但是无法获取数字。有什么建议吗?

text = "<:Valorant:946399790739099688><@&945697242994602054>"
start = text.find("<@&") + len("<@&")
end = text.find(">")
print(text[start:end])

您可以使用正则表达式搜索来提取第一个数字

>>> import re
>>> text = "<:Valorant:946399790739099688><@&945697242994602054>"
>>> m = re.search(':(\d+)', text)
>>> m.group(1)
'946399790739099688'

如果 id 是第二个数字,那么您可以使用

>>> m = re.search('@&(\d+)', text)
>>> m.group(1)
'945697242994602054'

如果您所有的字符串都是以下形式:

"<:Valorant:number1><@&number2>"

您可以使用以下代码段检索号码:

s = "<:Valorant:946399790739099688><@&945697242994602054>"
number1, number2 = map(int,s[11:-1].split("><@&"))
number1, number2
>>>> (946399790739099688, 945697242994602054)

如果格式总是一样的话,我会用split来提取东西:

text = "<:Valorant:946399790739099688><@&945697242994602054>"
id = text.split("><@&")[1].split(">")[0]
print(id)

混合使用 split 和 re 也是一个不错的选择,当事情变得更复杂时,它会非常强大。只需添加一个选项,已经提供了很多不错的选项。 :)

import re
text = "<:Valorant:946399790739099688><@&945697242994602054>"
o = re.split(r'[:>]|<@&', text)
print(o[1], o[2], o[4])
('Valorant', '946399790739099688', '945697242994602054')