Trouble adding blank space to a list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tooredrabbit
    New Member
    • May 2010
    • 6

    Trouble adding blank space to a list

    I'm a python newbie (in fact I'm a programming newbie). I'm teaching myself python for the fun of it by reading several online tutorials and then creating useless little scripts.

    For the past longer-than-I-would-care-to-admit I have been struggling to get this little bit of code to work:

    Code:
    for i in stringexp:
      if 'stringexp[i]' == '+':
        stringexp.insert[i, " "]
        stringexp.insert[(i + 1), " "]
    
    workingstring = "".join(stringexp)
        
    print workingstring
    When I print my "workingstr ing" I do not get spaces before and after '+' symbols. What am I doing wrong here?
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    The problem is a famous one! You can't fiddle with the thing you're iterating over. In your case you're fiddling with stringexp and iterating over it at the same time creating unpredictable results.

    There are several ways to achieve the same result though:
    Code:
    stringexp = stringexp.replace("+"," + ")
    is the easiest. There are many powerful string methods which are well worth getting familiar with.

    But supposing you really wanted to do it your way. There are several problems with your current code. Playing around on your command line is a helpful way of figuring this out. Also printing out the variables as you go helps clarify whether a variable is what you think it should be.

    Problem 1: "for i in stringexp:" assuming that stringexp is a string, then i is going to take on the various characters in the string in turn.
    Code:
    In [8]: for i in "hello, mum!":
       ...:     print i
       ...:     
       ...:     
    h
    e
    l
    l
    o
    ,
     
    m
    u
    m
    !
    This means that stringexp[i] has no meaning. What you really mean to say is
    Code:
    if i == '+'
    But actually you want i to be a number. So you could do this as follows:
    Code:
    for i in range(len(stringexp)):
    or you could do it this way:
    [CODE]In [10]: for i,char in enumerate("hell o, mum!"):
    print i, char
    ....:
    ....:
    0 h
    1 e
    2 l
    3 l
    4 o
    5 ,
    6
    7 m
    8 u
    9 m
    10 !
    /CODE]

    But this leads to the next problem. Suppose you inserted two characters into your string. Then the indexing would be off for the next insertion! One way around that is to do it backwards. The other way is to keep track of how many insertions you've made and adjust for it.

    Good luck!

    Comment

    • tooredrabbit
      New Member
      • May 2010
      • 6

      #3
      Thanks for the help! I'll hack away a bit and post the results here.

      Comment

      • tooredrabbit
        New Member
        • May 2010
        • 6

        #4
        The .replace thing works like magic.

        I'll tip my hand a bit: I'm trying to build a calculator that takes text input. This first step is just to take the input and create a list of the values and operators in order so that I can work with them later.

        After you mentioned the .replace idea I found a blog entry about how to do multiple replacements so that I can do this for multiple operators. My code looks like this:

        Code:
        fullstring = raw_input("What would you like to calculate?: ")
        
        def getlist(x):
          stringclip = x.replace(" ", "")
          oplist = {'+':' + ','-':' - ','*':' * ','/':' / ','(':' ( ',')':' ) ','^':' ^ '}
          ''' This replacement idea from http://gomputor.wordpress.com/ '''
          for i, j in oplist.iteritems():
            stringclip = stringclip.replace(i, j)
          return stringclip.split()
          
        print getlist(fullstring)
        Thanks for all the help.

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Oh, if you're trying to make a calculator, then python has just the command for you. "eval" will evaluate an expression. Check out the power:

          Code:
          In [1]: print eval("5+3*4")
          17
          
          In [2]: from math import *
          
          In [3]: print eval("sin(pi)*4")
          4.89842541529e-16
          
          In [4]: print eval("sin(pi/2)*4")
          4.0
          But with great power comes great responsibility - you need to be a little careful with this command and its cousin 'exec' because it's acting on user input.

          Good luck!

          Comment

          • tooredrabbit
            New Member
            • May 2010
            • 6

            #6
            Oh whoa.

            I had no idea about eval! Very cool. It makes me almost embarrassed that I've been writing this simple calculator (only handles the basic operators and has no error handling yet) that by now has evolved into using multiple 'for statements' and recursion. I think I'm reinventing the wheel (poorly).

            All of that being said, since my goal is to teach myself, my little pet project has been quite successful. I'm learning quite a bit (thanks for the help).

            Comment

            Working...