检查条件语句中的数据类型

如果它是整数,我想从字符串中打印一个字符。


这是我在为 Codewars 中的 Kata 编写的代码中的问题归零后编写的简化且具体的示例代码。虽然 Kata 在这里不相关,但我似乎无法弄清楚如何在条件语句(如if type(char) == int)中使用数据类型。


string = "th3is i1s anot4her ra2ndom strin5g"

for word in string:

    for char in word:

        if type(char) == int:

            print(char)


慕工程0101907
浏览 302回答 5
5回答

12345678_0001

你永远不会将你的字符串拆分成单词,所以外循环没有意义。您正在遍历字符,这些字符是长度为 1 的字符串。长度为 1 的字符串的类型永远不会等于int。你可以使用str.isdigit方法。用一个循环重写代码:for c in string:     if c.isdigit():            print(c)作为单线:print('\n'.join(c for c in string if c.isdigit()))

翻翻过去那场雪

我认为isdigit()可以工作,你也可以使用正则表达式。 https://www.w3schools.com/python/ref_string_isdigit.asp

四季花海

这可以使用正则表达式来完成,您可以re在 Python 中导入模块以使用正则表达式:import resentences = "th3is i1s anot4her ra2ndom strin5g"num = re.findall("[0-9]", sentences)print(num)基本上,此代码将返回该字符串中的所有数值

慕盖茨4494581

别担心.. 今天的每个高级程序员都曾经是初学者,因此会有所有明显的基本问题:)。您可以使用 str.isnumeric() 布尔检查。通过使用它,您可以避免第二个 for 循环,因为第二个 for 循环在这里实际上没有意义。这是修改后的代码-string = "th3is i1s anot4her ra2ndom strin5g"for char in string:    if char.isnumeric():        print(char)

交互式爱情

type但是,如果您输入type(<some variable>)进入解释器,你总是会得到类似于变量类型的"<class '<type'>" 形式的输出。<type>您可以实际使用此代码(这是一个示例,因此请根据您的目的修改它):myvar = "some python string"if type(myvar) == "<class 'str'>":&nbsp; &nbsp; # true&nbsp; &nbsp; print("Is a string")现在你可以想象,这个程序会输出>>> Its a stringstr您可以通过将块的一部分更改"<class 'str'>"为您要查找的类型(例如:"<class 'int'>"整数)来使其适用于任何类型。希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python