user3294540
user3294540

Reputation: 29

Python while loop with string

string = "Northeastern Africa"
myString = string.lower()
index = 0
num_index = int(index)

length = len(myString)
num_length = int(length)
num_length = num_length - 1

while myString[num_index] >=  myString[18]:
    print(num_index)
    print(num_length)
    print(myString[num_index])
    print(num_index)
    num_index = num_index +1
    print(myString[0:num_index])
    print(" ")

why does it only print "northeastern" and stops at the next space? how do i make it go through the full string without stopping at the space in between both words?

Upvotes: 0

Views: 13558

Answers (2)

Vivek Sable
Vivek Sable

Reputation: 10213

because myString[num_index] value is space check this..

>>> " ">="a"
False

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121744

Your while loop compares each character with the last, a, stopping when it finds a character that isn't equal or higher than a. Your code stops at the space because the latter's position in the ASCII table is 32:

>>> ' ' < 'a'
True
>>> ord(' ')
32
>>> ord('a')
97

You probably wanted to create a loop comparing num_index to num_length instead:

while num_index <= num_length:

If you wanted to loop through all characters in a string, just use a for loop:

for character in myString:
    print(character)

You can use the enumerate() function to add an index:

for index, character in enumerate(myString):
    print(index, character, sep=': ')
    print(myString[:index])

Upvotes: 1

Related Questions