简体   繁体   中英

Appending letters to a list in a while loop

I am trying to append the first word of a sentence to an empty list. The current code is below:

sentence = input("Enter sentence: ")

subject = []
print (subject)

x = 0
while True:
    letter = sentence[x]
    if letter != " ":
        print (letter)
        subject.append(letter)
        x = x + 1

print (subject)

It currently prints this:

Enter sentence: Cherries are red fruit

[]
C
h
e
r
r
i
e
s

It seems to ignore my attempt to append the result to the empty list... Help, please!

You'd better use for loop, it's less error-prone:

sentence = input('Enter sentence: ')

subject = []
print(subject)

for letter in sentence:
    if letter == ' ':
        break
    else:
        print(letter)
        subject.append(letter)

print(subject)

If you want to break a sentence into words, there's astr.split method, which can help you in simple cases:

words = sentence.split()
first_word = words[0] if words else None
print(first_word)

Why not use the split() function instead of appending one letter at a time:

sentence = input("Enter sentence: ")
split_sentence = sentence.split(" ")
subject = []
subject.append(split_sentence[0])
print (subject)

or even more simplier:

sentence = input("Enter sentence: ").split(" ")
subject = []
subject.append(sentence[0])
print (subject)

or even if you are only wanting one input you don't have to append

sentence = input("Enter sentence: ").split(" ")
subject = sentence[0]
print (subject)

split() , splits a string define by the parameter and returns a list.

With while loop:

sentence='Nice weather outside'
subject = []
x = 0
while x < len(sentence):
    letter = sentence[x]
    subject.append(letter)
    x = x + 1
print(subject)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM