python - 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
编辑:
我有一个建议,但我不知道怎么做。我为自己尝试并回到这里。
这需要明确地声明零索引大写是针对每个单词的。小伙伴们知道怎么做吗?
解决方案
所以我们可以分析您的代码并解释您输入的内容:
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))
推荐阅读
- r - 将 Excel 数字日期转换为 R 日期,但在某些行中只有给出的年份,例如“2018”而不是“43465”
- multithreading - 用mkldnn编译mxnet CPP包,支持单线程执行,无需环境变量
- javascript - 如何多查找聚合
- jenkins - 我们可以在用 Groovy 编写的 Jenkins 声明性管道的并行块中使用输入步骤吗?
- c++ - 有没有办法以clang格式禁用“SpacesInBraces”?
- .net - 通过命令管道后控制台重定向的问题
- c++ - 我可以为 nVIDIA GPU 编写 OpenCL-C++ 内核吗?
- autodesk-forge - CAD 文件的大小是否有任何限制,比如 Forge Viewer 可以显示的 RVT 文件?
- html - 如何修复 HTML 网页底部的空白?
- c# - Avro 序列化到 Azure EventHub