[英]How to solve the string indices must be integers problem in a for loop for capitalizing every word in a string
我希望每个人都安全。
我正在尝试对字符串进行 go 并将字符串的每个第一个字母大写。 我知道我可以使用.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”中有一个 integer 输入。 有什么帮助吗?
谢谢!
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[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) ,对应部分为您提供每个字符的索引,您可以使用它们! 我也删除了分割线,因为它是不必要的,你可以像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
in for word in string:
word 将遍历 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")
的 output 现在是"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)
笔记:
w[1:]
获取从字符索引 1 开始一直到字符串末尾的当前单词的 substring。 啊,还有function的arguments列表中的可选参数的用法……真是有用的东西要学。 如果你还不知道他们。 =)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.