converting the last word of a file into uppercase and writing the new content into a new file in Python

huangapple go评论73阅读模式
英文:

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(&#39;text.txt&#39;,&#39;r&#39;)
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(&quot;newfile.txt&quot;,&quot;w&quot;)
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()

huangapple
  • 本文由 发表于 2023年6月22日 01:19:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定