[英]In python How do i check whether a string starts with special symbol or not?
I wana check whether my string starts with a curly brace {. 我想检查我的弦是否以大括号{开头。 i tried the following code.
我尝试了以下代码。
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()
The file contains: {"name":"Chuvi"} 该文件包含:{“ name”:“ Chuvi”}
but my output is: No match 但我的输出是:不匹配
i even tried the following but dint get output 我什至尝试了以下内容,但得到了输出
if self.str[:0]=='{':
print "good match"
else:
print "No match"
In a slice, the end index is exclusive. 在切片中,结束索引是排他的。 Therefore,
self.str[:0]
always returns an empty string (it stops just before the zeroth character). 因此,
self.str[:0]
总是返回一个空字符串(它恰好在第零个字符之前停止)。
The correct way to write that slice is self.str[:1]
. 写入
self.str[:1]
的正确方法是self.str[:1]
。
A more idiomatic to perform the check is 进行检查的更惯用的方法是
self.str.startswith('{')
[:0]
gives you everything from the start of the string up to (but not including) the 0th character. [:0]
为您提供从字符串开头到第0个字符(但不包括第0个字符)的所有内容。 Hence it will always return '' (the empty string). 因此它将始终返回''(空字符串)。
You could use [0]
instead. 您可以改用
[0]
。 (ie if self.str[0] == '{'
) This would work, but would raise an exception if self.str is the empty string. (即,
if self.str[0] == '{'
)这将起作用,但是如果self.str是空字符串,则会引发异常。
So try [:1]
instead, which will get you the first character if one exists, or will give you '' if str is empty. 因此,请尝试使用
[:1]
,如果存在第一个字符,则将获取第一个字符;如果str为空,则将为您提供“''。
An alternative is to use if self.str.startswith('{')
. 另一种方法是使用
if self.str.startswith('{')
。 This will also do the right thing even if self.string
is an empty string. 即使
self.string
是一个空字符串,这也将做正确的事情。
you should use the startswith
method 您应该使用
startswith
方法
>>> "{a".startswith('{')
True
>>> "".startswith('{')
False
>>> "Fun".startswith('{')
False
you can use 您可以使用
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.