简体   繁体   English

查找用户在Python中输入的单词长度

[英]Finding Length of words input by user in Python

I am new in learning Python. 我是学习Python的新手。 And I thought of writing a code. 我想到了编写代码。

I want the user to input some words, and I want the program to give the length of the words as output. 我希望用户输入一些单词,并且我希望程序给出单词的长度作为输出。

words = [raw_input("Enter a name: ")]

def len_name(words):
    for x in words:
        print(x, len(x))

len_name(words)

Now, when the user gives a single word as input, say aeroplane, the program gives the following output and that's correct. 现在,当用户输入一个单词作为输入(例如飞机)时,程序将提供以下输出,这是正确的。

Enter a name: aeroplane
('aeroplane', 9)

But if user give two words as output, it give the following: 但是,如果用户输入两个单词作为输出,则会显示以下内容:

Enter a name: aeroplane, fish
('aeroplane, fish', 15)

I was looking for the code to give different words and their length. 我正在寻找给出不同单词及其长度的代码。

What did I mess up? 我搞砸了什么?

words = [raw_input("Enter a name: ")] takes the input and puts it in a list as a single element: ['aeroplane, fish'] . words = [raw_input("Enter a name: ")]接受输入并将其作为单个元素放入list中: ['aeroplane, fish'] In order to obtain ['aeroplane', 'fish'] , you need to split the input with an appropriate delimiter: 为了获得['aeroplane', 'fish'] ,您需要使用适当的定界符split输入:

words = raw_input("Enter a name: ").split(', ')
# or a little more robustly wrt white space:
words = [w.strip() for w in raw_input("Enter a name: ").split(',')]

You are current reading in a line, so it doesn't care about what is there in terms of spaces, or common separated words etc. 您当前正在一行中阅读,因此它不在乎空格或常见的分隔词等。

So you need to split the read in line into words using split 因此,您需要使用split将读入的行拆分为单词

A simple fix to your current code would be to not create a list for the multiple words since they are all one entry, and then .split(', ') that entry when its passed to len_name() and then do as you were with for i in x . 当前代码的一个简单解决方法是,不要为多个单词创建列表,因为它们都是一个条目,然后在将该条目传递给len_name()时执行.split(', ') ,然后按原样进行操作for i in x Also functions should return a value not just print. 函数也应该返回一个值,而不仅仅是打印。 A revised version would be: 修订版本为:

def len_name(x):
    lista = []
    for i in x.split(', '):
        lista.append((i, len(i)))
    return lista

words = input('Enter a name: ')
word_len = len_name(words)
for i in word_len:
    print(*i)
 Enter a name: vash, the, stampede vash 4 the 3 stampede 8 

Or using list comprehension and a loop to print 或者使用列表理解和循环进行打印

word_len = [(i, len(i)) for i in input('Enter a name: ').split(', ')]
for i in word_len:
    print(i[0], i[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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