我wana检查我的字符串是否以花括号开头{.我尝试了以下代码.
class parser(object):
def __init__(self):
self.fp=open('jsondata.txt','r')
self.str=self.fp.read()
print "Name of the file Opened is :",self.fp.name
print "Contents of the file :\n",self.str
def rule1(self):
var='{'
if self.str[:0]==var:
print "good match"
else:
print "No match"
obj=parser()
obj.rule1()
Run Code Online (Sandbox Code Playgroud)
该文件包含:{"name":"Chuvi"}
但我的输出是:不匹配
我甚至试过以下但是得到了输出
if self.str[:0]=='{':
print "good match"
else:
print "No match"
Run Code Online (Sandbox Code Playgroud)
在切片中,结束索引是独占的.因此,self.str[:0]始终返回一个空字符串(它在第0个字符之前停止).
编写该切片的正确方法是self.str[:1].
执行检查的更惯用的是
self.str.startswith('{')
Run Code Online (Sandbox Code Playgroud)