473,396 Members | 1,775 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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:

Expand|Select|Wrap|Line Numbers
  1. for i in stringexp:
  2.   if 'stringexp[i]' == '+':
  3.     stringexp.insert[i, " "]
  4.     stringexp.insert[(i + 1), " "]
  5.  
  6. workingstring = "".join(stringexp)
  7.  
  8. print workingstring
  9.  
When I print my "workingstring" I do not get spaces before and after '+' symbols. What am I doing wrong here?
May 26 '10 #1
5 8334
Glenton
391 Expert 256MB
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:
Expand|Select|Wrap|Line Numbers
  1. 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.
Expand|Select|Wrap|Line Numbers
  1. In [8]: for i in "hello, mum!":
  2.    ...:     print i
  3.    ...:     
  4.    ...:     
  5. h
  6. e
  7. l
  8. l
  9. o
  10. ,
  11.  
  12. m
  13. u
  14. m
  15. !
  16.  
This means that stringexp[i] has no meaning. What you really mean to say is
Expand|Select|Wrap|Line Numbers
  1. if i == '+'
But actually you want i to be a number. So you could do this as follows:
Expand|Select|Wrap|Line Numbers
  1. for i in range(len(stringexp)):
or you could do it this way:
[code]In [10]: for i,char in enumerate("hello, 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!
May 26 '10 #2
Thanks for the help! I'll hack away a bit and post the results here.
May 26 '10 #3
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:

Expand|Select|Wrap|Line Numbers
  1. fullstring = raw_input("What would you like to calculate?: ")
  2.  
  3. def getlist(x):
  4.   stringclip = x.replace(" ", "")
  5.   oplist = {'+':' + ','-':' - ','*':' * ','/':' / ','(':' ( ',')':' ) ','^':' ^ '}
  6.   ''' This replacement idea from http://gomputor.wordpress.com/ '''
  7.   for i, j in oplist.iteritems():
  8.     stringclip = stringclip.replace(i, j)
  9.   return stringclip.split()
  10.  
  11. print getlist(fullstring)
  12.  
Thanks for all the help.
May 26 '10 #4
Glenton
391 Expert 256MB
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:

Expand|Select|Wrap|Line Numbers
  1. In [1]: print eval("5+3*4")
  2. 17
  3.  
  4. In [2]: from math import *
  5.  
  6. In [3]: print eval("sin(pi)*4")
  7. 4.89842541529e-16
  8.  
  9. In [4]: print eval("sin(pi/2)*4")
  10. 4.0
  11.  
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!
May 27 '10 #5
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).
May 31 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: yukatan | last post by:
I have the following Javascript piece of code in a .js file (it's a function that generates a new html page with a button to call a function). var str = "hello"; // some code with (document) {...
6
by: zefri | last post by:
Hi, I want to create a simple css template like this : http://www.alsacreations.com/articles/modeles/g_fixe.htm But i've got a problem : the footer doesn't follow if contents(menu or center)...
12
by: micmic | last post by:
Dear all experts, I have the Coding as following: In File abc.cs namespace A { public class abc { public abc() {
2
by: Thomaz Pereira | last post by:
Hi; I use the method below to save the an image showed in a Picture Box using the SaveFileDialog. protected void SaveImage() { try { Stream stream = File.OpenWrite (this.CaminhoImagem);
2
by: Jet Leung | last post by:
When I debug my program and it return me an error call " have not handle ¡°System.StackOverflowException¡± appear in system.windows.forms.dll " How can I solve this problem??
8
by: MyAlias | last post by:
Can't solve this CallBack returning structures Error message: An unhandled exception of type 'System.NullReferenceException' occurred in MyTest.exe Additional information: Object reference not...
2
by: daemon | last post by:
I'm very sorry for the offtopic, but I haven't known where else to post. Can I solve n-order linear ode with gsl? Some like this: f(n)(x) - it's n-order derivative of f(x) A(n), B, D - scalar...
14
by: ToddLMorgan | last post by:
Summary: How should multiple (related) projects be arranged (structured) and configured so that the following is possible: o Sharing common code (one of the projects would be a "common" project...
2
by: Note Myself | last post by:
Today I wanted to solve an problem: I need to find out in the code if the iterator passed is a st::vector<T>::iterator, or std::vector<T>::reverse_iterator. I spent a lot of time tweaking a...
4
by: abhilash12 | last post by:
memory out of bound exception in javascript so pls tell me what is the reason
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.