Chuvi
Chuvi

Reputation: 1298

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"}
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"

Upvotes: 2

Views: 9008

Answers (4)

Ashif Abdulrahman
Ashif Abdulrahman

Reputation: 2147

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()   

Upvotes: 0

NPE
NPE

Reputation: 500475

In a slice, the end index is exclusive. Therefore, self.str[:0] always returns an empty string (it stops just before the zeroth character).

The correct way to write that slice is self.str[:1].

A more idiomatic to perform the check is

self.str.startswith('{')

Upvotes: 7

Bruce
Bruce

Reputation: 7132

you should use the startswith method

>>> "{a".startswith('{')
True
>>> "".startswith('{')
False
>>> "Fun".startswith('{')
False

Upvotes: 0

Jonathan Hartley
Jonathan Hartley

Reputation: 16034

[:0] gives you everything from the start of the string up to (but not including) the 0th character. Hence it will always return '' (the empty string).

You could use [0] instead. (i.e. if self.str[0] == '{') This would work, but would raise an exception if self.str is the empty string.

So try [:1] instead, which will get you the first character if one exists, or will give you '' if str is empty.

An alternative is to use if self.str.startswith('{'). This will also do the right thing even if self.string is an empty string.

Upvotes: 0

Related Questions