使用 len 作为文本但丢弃计数中的空格 [英] Using len for text but discarding spaces in the count

查看:39
本文介绍了使用 len 作为文本但丢弃计数中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试创建一个程序来计算用户输入的字符串中的字符数,但我想丢弃用户输入的任何空格.

def main():full_name = str(input("请输入全名:")).split(" ")对于全名中的 x:打印(len(x))主要的()

使用这个,我可以得到每个单词的字符数,没有空格,但我不知道如何将每个数字加在一起并打印总数.

解决方案

计算长度减去空格数:

<预><代码>>>>full_name = input("请输入全名:")请输入全名:john smith>>>len(full_name) - full_name.count(' ')9>>>len(全名)

So, I am trying to create a program which counts the number of characters in a string which the user inputs, but I want to discard any spaces that the user enters.

def main():
    full_name = str(input("Please enter in a full name: ")).split(" ")

    for x in full_name:
        print(len(x))


main()

Using this, I can get the number of the characters in each word, without spaces, but I don't know how to add each number together and print the total.

解决方案

Count the length and subtract the number of spaces:

>>> full_name = input("Please enter in a full name: ")
Please enter in a full name: john smith
>>> len(full_name) - full_name.count(' ')
9
>>> len(full_name)

这篇关于使用 len 作为文本但丢弃计数中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆