英文:
converting the last word of a file into uppercase and writing the new content into a new file in Python
问题
以下是您要翻译的内容:
OUTPUT
结果的截图
如您所见,大写转换未显示出来,相同的输出被写入到了新文件中,
谢谢!
英文:
Here is the code I tried!
the content in text.txt file is <this is a six worded sentence>
INPUT
file=open('text.txt','r')
file.seek(0)
a=file.read()
Lst = a.split()
print(Lst)
length=len(Lst)
print(Lst[length-1].upper())
Lst[length-1]).upper()
print(Lst)
#------------------------------#
newfile=open("newfile.txt","w")
newfile.writelines(Lst)
newfile.close()
file.close()
Output
screenshot of the result
as u can see the conversion of uppercase doesn't show up
and the same output gets written in newfile,
Thanks!
答案1
得分: 2
.upper()方法不会原地更改字符串,它会返回一个大写版本,所以你需要将它重新赋值给你的数组,例如:
Lst[length-1] = Lst[length-1].upper()
英文:
The .upper() call doesn't change the string in place, it returns an uppercase version, so you'd need to assign it back into your array e.g.:
Lst[length-1] = Lst[length-1].upper()
答案2
得分: 0
upper() 不会改变列表的元素,它只是返回大写后的值。要改变它,您必须将新值分配给该元素:
Lst[length-1] = Lst[length-1].upper()
英文:
upper() doesn't change the element of the list, it just returns the uppercased value. To change it you must assign to the element:
Lst[length-1] = Lst[length-1].upper()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论