Hello, I am still a newbie in python. I am trying to slice a string, but I don't know how.

def start():
     exp = "1+2";
     string1 = exp.split("+");

    print exp;
    print "Operator 1 is : " , op1;
    print "Operator 2 is : " , op2;

I want to output:
1+2
Operator 1 is : 1;
Operator 2 is : 2;

but the problem is I dont know how. will someone help me?.Thanks a lot in advance.

You dont need to use ; in python.

First we breake it down in python IDLE.

IDLE 2.6.4      
>>> exp = "1+2"
>>> exp
'1+2'
>>> string1 = exp.split("+")
>>> string1
['1', '2']
>>> print "Operator 1 is : " , op1
Operator 1 is : 

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    print "Operator 1 is : " , op1
NameError: name 'op1' is not defined
#just to get and error message "NameError" because we have nor defiend op1.

>>> print "Operator 1 is: %s  " % string1[0]
Operator 1 is: 1

So the finish script.

def start():
    exp = "1+2"
    string1 = exp.split("+")
    
    print "Operator 1 is: %s" % string1[0]
    print "Operator 2 is: %s" % string1[1]
    
start() 

'''Out-->
Operator 1 is: 1
Operator 2 is: 2
'''

what if the string is

exp="1+2-3"??

The next step is to use regular expressions (learn the re module)

import re
pat = re.compile(r"([+\-*/=]+)")
print(pat.split("1+2-3")) # prints ['1', '+', '2', '-', '3']

pat = re.compile(r"[+\-*/=]+")
print(pat.split("1+2-3")) # prints ['1', '2', '3']

If regular expressions are not sufficient, the next step is to use a parser like wisent (learn grammars and parsing computer languages).

Thank you very much!.. ^_^ . It is very helpful to me especially for a beginner like me about this language. Thank you. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.