[英]python 2.6.6 “phantom” whitespaces
基本上,我正在打开一些文件并从该文件的每一行中删除所有空格。 代码片段:
for filepath in filelist:
if filepath.endswith(".shader"):
shaderfile = open(filepath,"r").readlines()
for line in shaderfile:
line = Left(line, line.find("\n"))+"\n"
line = line.replace(" ","")
if line.find("common/")>-1:
print(line.replace("\n","\\n"))
根据要求,我删除了不太重要的代码。
发生了两件奇怪的事情:
1) 有些行以“\n\n”结尾
2)我得到这个 output:
textures/common/lightgrid\n
textures/common/mirror1
\n
textures/common/mirror2
\n
maptextures/common/invisible.tga
\n
textures/common/watercaulk
\n
textures/common/clipnokick
\n
textures/common/invisible\n
3)当我在这里粘贴 output 时,它看起来像:
textures/common/lightgrid\n
textures/common/mirror1\n
textures/common/mirror2\n
maptextures/common/invisible.tga\n
textures/common/watercaulk\n
textures/common/clipnokick\n
textures/common/invisible\n
我真的不知道发生了什么。 它是 print() 的错误吗? 抱歉格式错误,但这不是我的错,是stackoverflow的。
from StringIO import StringIO
a = StringIO("""textures/common/lightgrid
textures/common/mirror1
textures/common/mirror2
maptextures/common/invisible.tga
textures/common/watercaulk
textures/common/clipnokick
textures/common/invisible""")
def clean_lines(fileobj):
for line in fileobj:
if line:
line = line.strip()
if line:
yield "%s\n" % line
print [line for line in clean_lines(a)]
我使用 stringIO 来模拟一个文件,只需将 a 替换为您的 fileobj 是什么。
看来您想要 output 之类的
textures/common/lightgrid\ntextures/common/mirror1\n...
相反,你得到
textures/common/lightgrid\n
textures/common/mirror1\n
...
这是因为print
语句添加了一个隐式换行符。
您可以使用普通文件 output:
from sys import stdout
# ...
stdout.write("foo") # adds no implicit newline
您可以使用从 Python 3 移植回来的function print()
:
from __future__ import print_function
#
print("foo", end="") # use empty string instead of default newline
此外,如果您需要从字符串内部删除空格,您可以使其更简单并且可能更有效。
import re # regular expressions
whitespace_rx = re.compile(r"\s+") # matches any number of whitespace
# ...
splinters = whitespace_rx.split(raw_line) # "a b\nc" -> ['a','b','c']
compacted_line = "".join(splinters) # ['a','b','c'] -> 'abc'
当然,您可以用.split()
调用替换splinters
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.