首页 > 解决方案 > Int 和 str 更改每个带有错误的字母 + 编辑:零索引每个单词

问题描述

我的目标是编写一个函数,将每个偶数字母变为大写字母,奇数变为小写字母(空格也算作一个元素)。

这是我的代码

def to_weird_case(s):
    
    for i in s:
        if len(i) % 2 == 0:
            s[i] = i.upper() + s(i+1)
        else:
            s[i] = i.lower() + s(i+2)
        
        
        return i
            

我认为它应该是非常正确的,但它给了我错误。

 line 7, in to_weird_case
    s[i] = i.lower() + s(str(i)+2)
 TypeError: must be str, not int

编辑:

我有一个建议,但我不知道怎么做。我为自己尝试并回到这里。

这需要明确地声明零索引大写是针对每个单词的。小伙伴们知道怎么做吗?

标签: python

解决方案


所以我们可以分析您的代码并解释您输入的内容:

def to_weird_case(s):    
    for i in s: # s is your string, and i is the actual character
        if len(i) % 2 == 0: # if your length of the character can be divided by 2. Hmm this is weird
            s[i] = i.upper() + s(i+1) # s[i] change a character in the string but you should provide an index (i) so an integer and not a character. But this is not supported in Python.
        else:
            s[i] = i.lower() + s(i+2)
        
        
        return i # This will exit after first iteraction, so to_weird_case("this") will return "t".

所以你需要首先创建一个输出字符串并填充它。当迭代 s 时,您需要 char 的索引和 char 值本身。

def to_weird_case(s):    
  output = ""
  for i, myChar in enumerate(s):
      if i % 2 == 0:
          output += myChar.upper()
      else:
          output += myChar.lower()

  return output

my_sentence = "abcdef"
print(to_weird_case(my_sentence))

当您想忽略空格时,您需要跟踪实际字符(不包括空格)

def to_weird_case(s):
  output = ""

  count = 0  
  for myChar in s:
    if myChar.isspace():      
      output += myChar
    else:
      if count % 2 == 0:
          output += myChar.upper()
      else:
          output += myChar.lower()
      count += 1

  return output

my_sentence = "abc def"
print(to_weird_case(my_sentence))

推荐阅读