繁体   English   中英

如何在python中删除空字符串?

[英]How to remove empty string in python?

我不断收到ValueError: Could not convert string to float使用此代码时ValueError: Could not convert string to float

f = open('temperatuurid.txt')

while True:

    fahren = float(f.readline())
    print(round((fahren-32)*(5/9),2))

f.close()

如何删除.txt文档末尾的空字符串?

您可以尝试以下方法。

f = open('file')
m = f.readlines()
for i in m:
    if not i == '\n':
        fahren = float(i)
        print(fahren)
        print((fahren-32)*(5))
f.close()

从文档:

f.readline()从文件中读取一行; 换行符(\\ n)留在字符串的末尾,如果文件未以换行符结尾,则仅在文件的最后一行省略。 这使返回值明确。 如果f.readline()返回一个空字符串,则说明已到达文件的末尾,而空白行由'\\ n'表示,该字符串仅包含一个换行符。

因此它应该看起来像:

f = open('temperatuurid.txt')

for line in f.readLines():
    line = line.strip()
    if not line:
        continue
    fahren = float(line)
    print(round((fahren-32)*(5/9),2))

f.close()

f.readlines()返回文件中所有行的列表( while True是错误的)

if not line:确保我们读取了一个值。 该文档指出:

如果参数是字符串,则它必须包含一个可能带符号的十进制或浮点数,并可能嵌入在空格中。 ...如果未提供任何参数,则返回0.0。

ps:阿维纳什·拉吉(Avinash Raj)做到了正确,只是他不在乎行是否为空

假设空行实际上是空的:

print(*[round((float(line)-32)*(5/9),2) for line in f if line != '\n'])

也许是这样的:

f = open('temperatuurid.txt')

while True:
   line = f.readline().strip()
   fahren = float(line) if line else None
   print(round((fahren-32)*(5/9),2)) if line else None

f.close()

但这并不是要删除空字符串,而只是在我正确理解您的问题的情况下才将其忽略。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM