检查字符串是否包含数字的Python程序

Given a string and we have to check whether it contains only digits or not in Python.

给定一个字符串,我们必须检查它在Python中是否仅包含数字。

To check that a string contains only digits (or a string has a number) – we can use isdigit() function, it returns true, if all characters of the string are digits.

检查字符串是否仅包含数字 (或字符串包含数字 ),可以使用isdigit()函数 ,如果字符串的所有字符均为数字,则返回true 。

Syntax:

句法:

    string.isdigit()

Example:

例:

    Input:
    str1 = "8789"
    str2 = "Hello123"
    str3 = "123Hello"
    str4 = "123 456" #contains space 

    # function call
    str1.isdigit()
    str2.isdigit()
    str3.isdigit()
    str4.isdigit()

    Output:
    True
    False
    False
    False

Python code to check whether a strings contains a number or not

检查字符串是否包含数字的Python代码

# python program to check whether a string 
# contains only digits or not 

# variables declaration & initializations
str1 = "8789"
str2 = "Hello123"
str3 = "123Hello"
str4 = "123 456"    #contains space 

# checking
print("str1.isdigit(): ", str1.isdigit())
print("str2.isdigit(): ", str2.isdigit())
print("str3.isdigit(): ", str3.isdigit())
print("str4.isdigit(): ", str4.isdigit())

# checking & printing messages
if str1.isdigit():
    print("str1 contains a number")
else:
    print("str1 does not contain a number")

if str2.isdigit():
    print("str2 contains a number")
else:
    print("str2 does not contain a number")

if str3.isdigit():
    print("str3 contains a number")
else:
    print("str3 does not contain a number")

if str4.isdigit():
    print("str4 contains a number")
else:
    print("str4 does not contain a number")

Output

输出量

str1.isdigit():  True
str2.isdigit():  False
str3.isdigit():  False
str4.isdigit():  False
str1 contains a number
str2 does not contain a number
str3 does not contain a number
str4 does not contain a number


翻译自: https://www.includehelp.com/python/check-whether-a-string-contains-a-number-or-not.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值