Python2.7使用无意中的新行打印
对Python还是相当陌生的 我正在遍历一个文本文件:Python2.7使用无意中的新行打印,python,string,python-2.7,newline,line-breaks,Python,String,Python 2.7,Newline,Line Breaks,对Python还是相当陌生的 我正在遍历一个文本文件: 0x000B000A 0x000B000B 0x000B000C 将每一行附加到一个基本url,下面是代码中我遇到问题的特定部分: def ProcessID(id): url = baseUrl + "/" + id + "/" + type + "-" + id + "-" + version + "." + extension print "Processing: " + url for line in inputFile
0x000B000A
0x000B000B
0x000B000C
将每一行附加到一个基本url,下面是代码中我遇到问题的特定部分:
def ProcessID(id):
url = baseUrl + "/" + id + "/" + type + "-" + id + "-" + version + "." + extension
print "Processing: " + url
for line in inputFile:
ProcessID(line)
问题是,任何以A
或B
结尾的行都会在打印命令中添加换行符:
Processing: http://example.com/0x000B000A
/LST3-0x000B000A
-000000.ext
Processing: http://example.com/0x000B000B
/LST3-0x000B000B
-000000.ext
Processing: http://example.com/0x000B000C/LST3-0x000B000C-000000.ext
我做错了什么?这是否与Python解释字符串的方式有关(即Unicode 0A、0B)
谢谢,
PJ在这样的文件中迭代行时,行仍将包含最终换行符
'\n'
(如果之后没有空行,则最后一行除外)。最简单的方法就是脱掉它们:
for line in inputFile:
ProcessID(line.strip())
# OR: if you want to be more explicit and keep all other white space
ProcessID(line.rstrip('\n'))
你正在插入整行,包括它的中断。您应该将其从每行中删除。您可以执行
行。替换(“\n”,”)
啊!太好了,谢谢。我不知道。我们不能也使用replace
吗?@VanPeer当然可以,因为在此上下文中一行只能包含一个换行符。但是我会选择strip
,因为它更具体(并且不必搜索整行)。