Home > Software design >  How could I use the if function to verify if index count is true or false?
How could I use the if function to verify if index count is true or false?

Time:10-28

I have literally just begun self teaching some programming and decided to start with Python. As I've been going through the very first few exercises, I thought to myself how can I write something that tells me whether the index count of the string is what I think it is? Something along the lines of

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

I know it's mega noob stuff but I was curious cos I couldn't do it myself and couldn't find similar questions or probably really understand those that were. Cheers all

EDIT:thank you all for the helpful answers! interesting to see there are multiple paths to the same solution. cheers!

CodePudding user response:

my_string = "Hello world"
if (my_string[0] == "H"):
    print(True)
else:
    print(False)

my_string[0] accesses the 0th element (character) in the word, and the == is the comparator

CodePudding user response:

You can look for string index(). It returns the index of a character in the string.

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

CodePudding user response:

WelCome to the wonderfull world of PowerShell.

The PowerShell way could be like this:

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

indexOf("H") returns the index position of H in this case 0. Compare that with the -eq parameter and you're done.

  • Related