【问题标题】:How could I use the if function to verify if index count is true or false?我如何使用 if 函数来验证索引计数是真还是假?
【发布时间】:2021-10-27 05:56:18
【问题描述】:

我刚刚开始自学一些编程,并决定从 Python 开始。 当我经历了最初的几个练习时,我在想,我怎样才能写出一些东西来告诉我字符串的索引计数是否是我认为的那样?类似于

astring = "Hello world!"
if (astring.index ("H") = 0) = True
print true

我知道这是超级菜鸟的东西,但我很好奇,因为我自己做不到,也找不到类似的问题,或者可能真的理解那些问题。祝大家好运

编辑:谢谢大家的有用答案!有趣的是,同一个解决方案有多种路径。干杯!

【问题讨论】:

    标签: string if-statement indexing printing


    【解决方案1】:
    my_string = "Hello world"
    if (my_string[0] == "H"):
        print(True)
    else:
        print(False)
    

    my_string[0] 访问单词中的第 0 个元素(字符),== 是比较器

    【讨论】:

      【解决方案2】:

      您可以查找string index()。它返回字符串中字符的索引。

      if (astring.index("H")) == 0:
         print("True")
      

      【讨论】:

        【解决方案3】:

        欢迎来到 PowerShell 的奇妙世界。

        PowerShell 方式可能是这样的:

        $string = "Hello World"
        If ($string.indexof("H") -eq 0) {"Do Something"}
        

        indexOf("H") 在这种情况下返回 H 的索引位置 0。将其与 -eq 参数进行比较即可。

        【讨论】:

        • 我似乎无法让这个方法工作,它在 0 处给我一个语法错误
        • 让它以这种方式工作 if (astring.index("H") == 0): print ("Do Something") using indexof 给出了错误:Traceback(最近一次调用最后一次): 中的文件“”,第 2 行 if (astring.indexof("H") == 0): print ("Do Something") AttributeError: 'str' object has no attribute 'indexof'跨度>
        猜你喜欢
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        • 2010-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多