[英]Python: str.startswith() and string comparison “==” not working
I'm trying to read a string from a file and find words that start with "'param."
我正在尝试从文件中读取字符串,并找到以
"'param."
开头的单词"'param."
This is my code: 这是我的代码:
# -*- coding: utf-8 -*-
inputfile = open('abc.json', 'r')
fieldnametemp = []
for line in inputfile:
for word in line.split():
if(word == "'fieldname':"):
fieldnametemp.append(line.split(':')[1])
for element in fieldnametemp:
print element
if(element.startswith("'param.")):
print 1
else:
print 0
And this is my output: 这是我的输出:
'param.design_key',
0
'param.abc',
0
'param.def',
0
Even if its start with "'param." 即使以“'param”开头。 it prints 0.
它显示0。
I also tried to use 我也尝试使用
if(element.split('.')[0] == "'param."):
instead of 代替
if(element.startswith("'param.")):
but output is same. 但输出是相同的。 What's wrong and what can I do?
怎么了,我该怎么办?
Based on this 基于此
for word in line.split():
if(word == "'fieldname':"):
fieldnametemp.append(line.split(':')[1])
every element in fieldnametemp
starts with a whitespace. fieldnametemp
每个元素都以空格开头。 So the content of element
when you do element.startswith("'param.")
also starts with a whitespace, so you are actually doing: 因此,当您执行
element.startswith("'param.")
时, element
的内容也以空格开头,因此您实际上是在做:
" 'param.abc'".startswith("'.param")
which is obviously false. 这显然是错误的。 you need to include the whitespace:
您需要包括空格:
element.startswith(" 'param.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.