在while循环中将字母附加到列表中

时间:2016-10-03 16:46:25

标签: python while-loop append

我试图将句子的第一个单词附加到空列表中。目前的代码如下:

    bool exclusive;
    System.Threading.Mutex appMutex = new System.Threading.Mutex(true, "MyAppName", out exclusive);
    if (!exclusive)
    {
      //Another instance running
    }    ...
    GC.KeepAlive(appMutex);

目前打印出来:

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)

似乎忽略了我将结果附加到空列表的尝试...请帮助!

3 个答案:

答案 0 :(得分:2)

您最好使用for循环,它不易出错:

sentence = input('Enter sentence: ')

subject = []
print(subject)

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

print(subject)

如果你想将一个句子分成单词,可以使用str.split方法,它可以在简单的情况下帮助你:

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

答案 1 :(得分:0)

为什么不使用split()功能,而不是一次附加一个字母:

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

甚至更简单:

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

或者即使您只想要一个输入,也不必附加

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

split(),拆分由参数定义的字符串并返回一个列表。

答案 2 :(得分:0)

有循环:

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