我在pycharm上创建了一个程序,允许用户输入一个数字,这样就可以创建一个项目列表。该计划如下:
item = int(input("How many items do you want in your list? "))
stringList = []
for i in range(1, item +1):
stringList.append(input("Enter String {0}: ".format(i)))
print(stringList)
可以输出的示例显示如下:
How many items do you want in your list? 3
Enter String 1: apple
Enter String 2: banana
Enter String 3: grape
['apple', 'banana', 'grape']
我现在要做的是添加用户输入的每个字符串的长度。我是python的新手,想知道如何添加长度,所以输出将是这样的:
Enter String 1: apple
Enter String 2: banana
Enter String 3: grape
['apple', 'banana', 'grape']
The length of the string 'apple' is 5
The length of the string 'banana' is 6
The length of the string 'grape' is 5
The total length of all strings is 21
答案 0 :(得分:0)
使用len(string_var)
这将返回字符串string_var
您可以添加以下代码:
for i in range(1, item +1):
stringList.append(input("Enter String {0}: ".format(i)))
print(stringList)
total_str_length = 0
for each_string in stringList:
print("The length of the string '%s' is %s") %(each_string, len(each_string))
total_str_length += len(each_string)
print("The total length of all strings is %s") % total_str_length
这将打印stringList格式化为预期输出的每个字符串。
答案 1 :(得分:0)
这是我在调整给出的反馈后得出的答案:
item = int(input("How many items do you want in your list? "))
itemnum = []
for i in range(1, item +1):
itemnum.append(input("Enter String {0}: ".format(i)))
print(itemnum)
totalLength = 0
for eachString in itemnum:
print("The length of the string",(eachString), "is :", len(eachString))
totalLength += len(eachString)
print("The total length of all strings is:", totalLength)
输出结果是:
How many items do you want in your list? 4
Enter String 1: red
Enter String 2: blue
Enter String 3: green
Enter String 4: yellow
['red', 'blue', 'green', 'yellow']
The length of the string red is : 3
The length of the string blue is : 4
The length of the string green is : 5
The length of the string yellow is : 6
The total length of all strings is: 18
答案 2 :(得分:-1)
Manish的答案最容易理解,但作为一个单行解决方案,您可以这样做,在您构建列表之后将所有内容添加到一起:
total_length = sum(len(word) for word in stringList)