本文介绍了在列表中切割字符串的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这是我写的代码: file = open(''C:\switches.txt'',''r'') switches = file.readlines() i = 0 for line in switch: line = switches [我] [: - 1] i + = 1 打印开关 你可以告诉我在做什么。从文件中读取一个行列表, 然后我想从每一行切掉''\ n''字符。但是这个代码运行后, ,\ n仍然存在。我认为它可能有一些与字符串是不可变的事实有关的事情,但是测试 如: 开关[0] [: - 1] 确实切掉了\ n字符。所以我猜问题就在于 作业或其中某处。 另外,这是索引列表的最佳方法吗?Here''s the code I wrote:file = open(''C:\switches.txt'', ''r'')switches = file.readlines()i = 0for line in switches:line = switches[i][:-1]i += 1print switchesYou can probably tell what I''m doing. Read a list of lines from a file,and then I want to slice off the ''\n'' character from each line. Butafter this code runs, the \n is still there. I thought it might havesomething to do with the fact that strings are immutable, but a testsuch as:switches[0][:-1]does slice off the \n character. So I guess the problem lies in theassignment or somewhere in there.Also, is this the best way to index the list?推荐答案 ' 'Hello world!'' 所以我猜问题就在于任务或其中的某个地方。 是的。您将重复将新的字符串实例分配给line,然后再次引用。如果你想更新开关 list,那么不要分配给line。在循环内,你需要: 开关[i] =开关[i] [: - 1] 另外,这是最好的索引方式列表?''Hello world!'' So I guess the problem lies in the assignment or somewhere in there.Yes. You are repeated assigning a new string instance to "line", whichis then never referenced again. If you want to update the switcheslist, then instead of assigning to "line" inside the loop, you need:switches[i] = switches[i][:-1] Also, is this the best way to index the list? 否,因为行变量未使用。这个: i = 0 for line in switch: line = switches [i] [: - 1] i + = 1 写得更好: for i in range(len(switches)): 开关[i] =开关[i] [: - 1] 对于Python中的大多数循环场景,你不必手动 增加一个计数器变量。 --Ben PS - 实际上,你可以完成以上所有在一行 代码: 打印[line [: - 1] for line in open(''C:\\switches.txt'') ]No, since the line variable is unused. This:i = 0for line in switches:line = switches[i][:-1]i += 1Would be better written as:for i in range(len(switches)):switches[i] = switches[i][:-1]For most looping scenarios in Python, you shouldn''t have to manuallyincrement a counter variable.--BenPS - actually, you can accomplish all of the above in a single line ofcode:print [line[:-1] for line in open(''C:\\switches.txt'')] 哇,刚刚更换7行代码!所以*这就是为什么Python是好的b 。 :)Wow, that just replaced 7 lines of code! So *this* is why Python isgood. :) 嗯,我刚刚在原始代码中意识到我没有逃脱 反斜杠。为什么它仍能正常工作? 顺便说一下,整个''一行'的东西让我大吃一惊。当我开始研究列表理解时,我并没有想到列表理解,但 只是事实上它可以在一行中完成所有这一切都是惊人的。我在C#中尝试了这个,当然我必须先创建一个类,然后打开 文件流等等。:) 我是否在开放功能中不需要''r''参数?Hmm, I just realized in my original code that I didn''t escape thebackslash. Why did it still work properly?By the way, this whole ''one line'' thing has blown me away. I wasn''tthinking about list comprehensions when I started working on this, butjust the fact that it can all be done in one line is amazing. I triedthis in C# and of course I had to create a class first, and open thefile streams, etc. :)And do I not need the ''r'' parameter in the open function? 这篇关于在列表中切割字符串的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-05 18:10