将字符串字母分解为奇数和偶数字符

时间:2019-04-03 19:39:42

标签: python string character break

大家下午, 我在尝试将字符串中输入的单词分成奇数和偶数类别时遇到一些问题。该问题应该返回具有奇数和偶数字母分配给那些相应分支的两个输出值。

现在,我进行了一些试验,在该试验中,将字符串硬编码到wordStr中,其余过程似乎在此下运行顺利。因此,我觉得我必须在程序中附加一些其他内容才能注册用户输入。代码如下所示:

def oddEvenWord():

    #Objective: program will print out the seperate characters included within a string under where they fall placement wise, odd or even

    wordstr = eval(input("Please enter a word to be broken apart into odd and even characters:"))

    even_letters = ""
    odd_letters = ""
    lword = len(word)
    index = 0


    for index in range(0,len(word)):
        if int(index) % 2 == 0:
            even_letters += word[index]

        else:
            odd_letters += word[index]

    print(list(even_letters), end = ' ')
    print(list(odd_letters), end = ' ')

oddEvenWord()
像我上面提到的那样,该程序应该能够区分用户输入的单词中的奇数字符和偶数字符,但是该模块无法将其识别为有效字符串,并使回调无效。如果有人可以给我这个部门的一些指示,我将不胜感激

2 个答案:

答案 0 :(得分:0)

通过调用eval,您会将输入字符串视为Python代码,但不是,因此请不要调用eval。您还应该命名接收变量word而不是wordstr,以使其与其余代码保持一致:

更改:

wordstr = eval(input("Please enter a word to be broken apart into odd and even characters:"))

收件人:

word = input("Please enter a word to be broken apart into odd and even characters:")

答案 1 :(得分:0)

要获取多个带空格的单词,可以使用 raw_input()

如下,

word = raw_input("Please enter a word to be broken apart into odd and even characters:")

否则,在输入输入字符串时要注意不要忘记键入"" 正如@blhsing在他的回答中提到的那样,您应该删除 eval 并将 wordstr 替换为 word

甚至您也可以像下面这样在python衬里中进行操作:

一个衬里的任何一个

a=lambda x:[[x[o] for o in range(len(x)-1) if not o%2],[x[e] for e in range(len(x)-1) if e%2 ]]

a=lambda x:[[o for o in x[::2]],[e for e in x[1::2]  ]]

然后

word = raw_input("Please enter a word to be broken apart into odd and even characters:")
print(a(word))