【问题标题】:Output of program for user input giving different length for consonant with user input. input 1 --> abc input2--> 'abc'用户输入程序的输出为用户输入的辅音提供不同的长度。输入 1 --> abc 输入 2--> 'abc'
【发布时间】:2016-07-19 02:09:05
【问题描述】:

""" 为什么这 4 在第二个用户输入为 'abc'.ii 知道它正在计算引号,因为 python 会将输入 'abc' 视为 "'abc'" 因此将 5 作为长度计算如何解决这个问题像上面所示的其他输入一样得到正确的答案n下面"""

计算元音 n 辅音

 def get_count(words):
    words=str(input('Enter:')).lower()
    vowels = ['a','e','i','o','u']
    v_count = 0
    c_count = 0
    for letter in words:
        if letter in vowels:
            v_count += 1
        else:
            c_count+=1
    print("vowel : {}".format(v_count), "consonant: {}".format(c_count))
get_count(input)

Result:

Enter:aBc
vowel : 1 consonant: 2
Enter:'abc'
vowel : 1 consonant: 4-  ??? why

块引用

Enter:abc
vowel : 1 consonant: 2

【问题讨论】:

  • 还有..,问题是什么
  • 所以 words=str(input('Enter:')).lower() 现在当我输入时 - abc len 操作给出的长度是 3 很好,但是当我输入 'abc' len 操作给出长度 5 .为什么 ??这是我在我的程序中抛出错误
  • 嗨,我希望我能够正确传达:- x=len(abc) 是 3 而 x=len('abc') 是 5 当用户输入用于程序时?如何解决这个问题

标签: python string python-3.x string-length


【解决方案1】:

长答案:所以你的字符串是 'abc' ,它有 5 个字符长。 python 正在检查:

  • 如果第一个字符 ' 在元音中并且它是 不那么辅音 = 0+1
  • 第二个字符是a,它在元音中,所以 元音 = 0+1
  • 第三个b不在元音中,所以辅音=1+1 (现在是 2 个)
  • 第四个c不在元音中,所以辅音= 2+1(现在是 3)
  • 第五个字符是',它不在元音中, 所以辅音 = 3+1(现在是 4)

所以最后我们得到:元音:1 辅音:4

简短回答:您的输入被视为一个五字符长的字符串,您的脚本会遍历每个元素,包括单引号。

【讨论】:

  • andriyze -- 你的解释真的很棒。我对 python 计算“'”也是字符的一部分这一事实感到困惑
【解决方案2】:

你应该先判断字符是否在字母表中。

def get_count(words):
    words=str(input('Enter:'))
    vowels = ['a','e','i','o','u']
    v_count = 0
    c_count = 0
    for char in words:
        if char.isalpha():
            if char.lower() in vowels:
                v_count += 1
            else:
                c_count+=1
    print("vowel : {}".format(v_count), "consonant: {}".format(c_count))
get_count(input)

【讨论】:

  • 谢谢蒂索加。这个添加字符字母表的东西有效。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多