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



我希望每个人都安全。

我正在尝试遍历一个字符串并将字符串的每个首字母大写。 我知道我可以使用 .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:字符串索引必须是整数",即使我在"word"中有一个整数输入。有什么帮助吗?

谢谢!

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

首先,您拆分字符串只是为了计算单词数,但不要存储它以在此之后操作单词。

其次,当迭代带有forin的字符串时,你得到的是字符串的字符,而不是单词。

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

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技巧...第一个是返回元组 (i, j( 的枚举(可迭代(,其中 i 是位置索引,j 是该位置的值。其次,我使用w[1:]获取当前单词的子字符串,该子字符串从字符索引 1 开始,一直到字符串的末尾。啊,还有函数参数列表中可选参数的使用......真正有用的东西要学习!如果你还不认识他们。=)

您的代码中存在逻辑错误: 你用了 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
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该字符串是您正在访问的字符串word正在使用string[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()))

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. 

看,在你的代码,word是一个字符串的字符,它不是索引,因此你不能使用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

在这里,我将字符串中单词的第三行更改为len(string(中的单词,对应物为您提供每个字符的索引,您可以使用它们! 我也删除了分割线,因为它是不必要的,你可以像len(string(一样对循环进行操作

最新更新