将文件中的行与字符串进行比较 [英] compare lines in a file with a string
问题描述
我正在尝试查看我的列表中是否已包含特定用户.我应该打印出找到匹配项",但我没有.我认为问题出在我的 php 文件中,所以我创建了一个具有相同内容的文本文件,但仍然找不到匹配项.
I'm trying to see if my list already has a specific user in it. I should get "match found" printed out but I don't. I thought the problem was in my php-file so i created a text file with the same contents but it still doesn't find the match.
import urllib2
server = "10.20.68.235"
var = "patrik"
file = urllib2.urlopen("http://"+server+"/list-text.php")
for line in file:
if line == var:
print "match found"
print line,
print "done"
这是我得到的输出:
someguy
user
patrik
juniper
ftpsecure
momeunier
done
推荐答案
如果创建以下文件 xx.in
:
test line 1
test line 2
并运行以下 Python 程序,您将看到正是匹配失败的原因:
and run the following Python program, you'll see exactly why the match is failing:
file = open('xx.in')
for line in file:
print '[%s]' % (line)
输出为:
[test line 1
]
[test line 2
]
显示换行符在读入时保留在行上.如果您希望将它们剥离,可以使用:
showing that the newline characters are being left on the line when they're read in. If you want them stripped off, you can use:
line = line.rstrip('\n')
这将从字符串的 end 中删除所有换行符,并且与 strip()
不同,不会影响开头或结尾的任何其他空白字符.
This will remove all newline characters from the end of the string and, unlike strip()
, will not affect any other whitespace characters at either the start or end.
这篇关于将文件中的行与字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!