如何解决 for 循环中的字符串索引必须是整数问题,以将字符串中的每个单词大写

How to solve the string indices must be integers problem in a for loop for capitalizing every word in a string

希望大家都平安。

我正在尝试检查一个字符串并将该字符串的每个首字母大写。 我知道我可以使用 .title() 但是

a) 我想弄清楚在这种情况下如何使用大写字母或其他东西 - 基础知识,以及

b) 测试中的字符串,有一些带有 (') 的单词,这使得 .title() 混淆并将 (') 后面的字母大写。

def to_jaden_case(string):
    appended_string = ''
    word = len(string.split())
    for word in string:
       new_word = string[word].capitalize()
       appended_string +=str(new_word)
    return appended_string

问题是解释器给了我 "TypeError: string indices must be integers" 即使我在 'word' 中有一个整数输入。有帮助吗?

谢谢!

from re import findall

def capitalize_words(string):
    words = findall(r'\w+[\']*\w+', string)
    for word in words:
        string = string.replace(word, word.capitalize())
    return string

这只是抓取字符串中的所有单词,然后替换原始字符串中的单词,[]中的字符也会被包含在单词中

您正在使用字符串索引访问另一个字符串 word 是您正在使用 string[word] 访问 word 的字符串,这导致了错误。

def to_jaden_case(string):
   appended_string = ''
   for word in string.split():
       new_word = word.capitalize()
       appended_string += new_word
   return appended_string

使用map()

的简单解决方案
def to_jaden_case(string):
    return ' '.join(map(str.capitalize, string.split()))

你看,你的代码中word是string的一个字符,不是索引,所以不能用string[word],可以通过修改来解决这个问题你的循环或使用 word 而不是 string[word]

因此您的修正代码将是:

def to_jaden_case(string):
    appended_string = ''
    for word in range(len(string)): 
        new_word = string[word].capitalize()
        appended_string +=str(new_word)
    return appended_string

这里我把第三行for word in string改成for word in len(string),对方给你索引每个角色,你都可以使用它们! 我还删除了 split 行,因为它是不必要的,你可以像 len(string)

您的代码存在逻辑错误: 您使用了 word = len(string.split()) 没有用,而且 for 循环逻辑中也存在问题。

试试下面这个:

def to_jaden_case(string):
    appended_string = ''
    word_list = string.split()
    for i in range(len(word_list)):
        new_word = word_list[i].capitalize()
        appended_string += str(new_word) + " "
    return appended_string

for word in string: 中,单词将遍历 string 中的字符。你想要做的是这样的:

def to_jaden_case(string):
    appended_string = ''
    splitted_string = string.split()
    for word in splitted_string:
        new_word = word.capitalize()
        appended_string += new_word
    return appended_string

to_jaden_case("abc def ghi") 的输出现在是 "AbcDefGhi",这是 CammelCase。我想你真的想要这个:"Abc Def Ghi"。为此,您必须:

def to_jaden_case(string):
    appended_string = ''
    splitted_string = string.split()
    for word in splitted_string:
        new_word = word.capitalize()
        appended_string += new_word + " "
    return appended_string[:-1]  # removes the last space. 

你在代码中做了一些奇怪的事情。

首先,你分割字符串只是为了计算单词的数量,但不要存储它来操作之后的单词。

其次,当用 for in 迭代字符串时,你得到的是字符串的字符,而不是单词。

我做了一个小片段来帮助你做你想做的事:

def first_letter_of_word_upper(string, exclusions=["a", "the"]):
    words = string.split()
    for i, w in enumerate(words):
        if w not in exclusions:
            words[i] = w[0].upper() + w[1:]
    return " ".join(words)

test = first_letter_of_word_upper("miguel angelo santos bicudo")
test2 = first_letter_of_word_upper("doing a bunch of things", ["a", "of"])

print(test)
print(test2)

备注:

  • 我将字符串拆分的值赋给了一个变量,以便在循环中使用它
  • 作为奖励,我提供了一个列表,让您可以排除不想大写的单词。
  • 我使用原来相同的拆分词数组来构建结果...然后基于该数组进行连接。这是一种高效的方式。
  • 此外,我展示了一些有用的 Python 技巧...首先是枚举(可迭代) returns 元组 (i, j) 其中 i 是位置索引,j 是值在那个位置。其次,我使用 w[1:] 获取当前单词的子字符串,该子字符串从字符索引 1 开始,一直到字符串的末尾。啊,还有函数参数列表中可选参数的用法……真的很有用,值得学习!如果你还不认识他们。 =)