简体   繁体   English

检查字符串是否在python中包含数字

[英]check if a string contains a digit in python

I am checking a string in python for a digit. 我正在检查python中的字符串是否为数字。 I have used the is_digit() method but doesnt look like it works. 我使用过is_digit()方法,但看起来不起作用。 this is my string 302 E 34th 101 so i want to check if the last split of the string is a digit and if true,cut it and assign it to a value. 这是我的字符串302 E 34th 101,所以我想检查字符串的最后一个分割是否为数字,如果为true,则将其剪切并将其分配给一个值。 here is my code 这是我的代码

if split("302 E 34th 101")[-1].is_digit():
  digit=split("302 E 34th 101")[-1]

this doesnt seem to work as expected since it does not return result. 这似乎没有按预期方式工作,因为它没有返回结果。 Does anyone know the best way to do this? 有谁知道最好的方法吗? maybe using a regular expression? 也许使用正则表达式? Thanks in advance. 提前致谢。

It seems that you are using a custom split function which doesn't split the string properly. 似乎您正在使用自定义split功能,该功能无法正确拆分字符串。 Instead you can use str.split method and use isdigit() for validating the digit format: 相反,您可以使用str.split方法并使用isdigit()来验证数字格式:

>>> s.split()[-1]
'101'
>>> s.split()[-1].isdigit()
True

That's just not how you split in python. 那不是您在python中拆分的方式。 You need to call the method on the string object like this: 您需要像这样在字符串对象上调用方法:

if "302 E 34th 101".split()[-1].isdigit():
    digit = "302 E 34th 101".split()[-1]

Here's a link to the docs 这是文档的链接

You can rsplit or rfind if you always want to check based on whitespace: 如果您始终想根据空白进行检查,则可以rsplitrfind

s = "302 E 34th 101"
print(s[s.rfind(" "):].isdigit())

print(s.rsplit(None,1)[-1].isdigit())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM