Not*_*Spy -1 python indexing for-loop list
我正在尝试使用一些 for 循环来取一个句子并将每个单词的第一个字母大写。
p1 = "the cat in the hat"
def title_creator(p1):
p = p1.split()
p_len = len(p)
d = []
for i in range(p_len):
first_letter = p[i][0]
m = first_letter.upper()
d.append(m)
p[i][0] == d[i]
p = " ".join(p)
return p
z = title_creator(p1)
print(z)
Run Code Online (Sandbox Code Playgroud)
这从顶部输出相同的原始句子。我如何能够将索引从一个列表替换为另一个列表?
-ps 如果这个问题真的很简单,我很抱歉,我只是忽略了一些简单的事情。
使用标题():
p1 = "the cat in the hat"
print(p1.title())
# The Cat In The Hat
Run Code Online (Sandbox Code Playgroud)
编辑:
以防万一您想尝试使用 for 循环,您可以像这样使用它:
p1 = "the cat in the hat"
def title_creator(p1):
p = p1.split()
for index, element in enumerate(p):
p[index] = element.capitalize()
result = " ".join(p)
return result
z = title_creator(p1)
print(z)
Run Code Online (Sandbox Code Playgroud)