I am learning Python by trying to code up a simple adventure game. I have created a while loop to get a choice of direction from the user and I am clearly not doing it in an efficient way. I have created a while loop with multiple 'or' conditions to keep looping until the user provides one of the four valid directions as input. Unfortunately this extends the line beyond 80 characters with the tab. What is the best way to either break this line onto two lines so as not to get a syntax error or write this sort of loop more efficiently?  while direction != "N" or direction != "S" or direction != "E" or direction != "W":     if direction == "N":         print "You went N to the Mountain Pass"         return 'mountain'      elif direction == "S":         print "You went S to the Shire"         return 'shire'      elif direction == ...   When I try to break the first line into two, no matter where I break it I get  a syntax error...    File "sct_game1.py", line 71   while direction != "N" or direction != "S" or                                               ^ SyntaxError: invalid syntax   I'm open to suggestions on how to break the line successfully, or even better, writing this loop more efficiently.  Thanks.
4322
I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?  For example, adding a bunch of strings,  e = 'a' + 'b' + 'c' + 'd'   and have it in two lines like this:  e = 'a' + 'b' +     'c' + 'd'
58455
I have a problem with a lstlisting environment. I want to use it for displaying several very long lines that can not be reformatted. Independently of the option breakatwhitespace=true or false my lines are not broken down so that the end is far outside of the printable area.  How to specify that line breaks are allowed at any character? Or is it possible to specify the characters (besides whitespace) that can be used for a line break?  Alternative: inserting a special (not-printed) character that indicates "break line here" - doe something like this exists?  \begin{lstlisting}[] Test1: 33b7a2f7c4cc93c46dd4ee2ed81aa1eb-9409135542c79d1ed50c9fde07fa600a_cce5a2fe76bfbd0c48d79fb43a7106f0_263e9a8711c1400fb2a716a1b820ac9a Test2: 33b7a2f7c4cc93c46dd2423423423423-9409135542c79d1ed50c9fde07fa600a_cce5a2fe76bfbd0c48d79fb43a7106f0_263e9a8711c1400fb2a716a1b820ac9a \end{lstlisting}   Update:  The  works fine. Additionally I found a different approach which works directly with a lstlisting environment:  \begin{lstlisting}[breakatwhitespace=true, literate={\-}{}{0\discretionary{-}{\\}{}}]   ... \end{lstlisting}   It allows to break the lines also at hyphenations. It has some drawbacks especially that the line breaks are looking different from the others in the environment. But may be for others this code may be helpful...  Found here:
6617
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.  What is the best way to do this, within the following code?  f = open(file) for line in f:     if line.contains('foo'):         newline = line.replace('foo', 'bar')         # how to write this newline back to the file
23155
I am trying to write some pseudocode. How can I add two line to the algorithm at the top and the bottom as well as adding line number.  Code:  \documentclass{article} %\usepackage{algorithmic}% http://ctan.org/pkg/algorithms \usepackage[]{algorithm2e} \begin{document} \begin{algorithm}[H] \SetAlgoLined \KwData{latitude, longitude, mac, route, direction} %\KwResult{how to write algorithm with \LaTeX2e }  initialize $list$ as an empty  list of integers. \\ %\While{not at end of this document}{ %read current\; $list$ = Get stop Order from behaviour; \\ \eIf{list size &gt; 0}{   find the last stop name in the behaviour table of this mac; }{   find the closet stop of the producer current location; \\   insert it into next table; \\   find initializer; \\   \eIf{initializer is available}{      get the initializer stop name;  \\      restore all stop name for this mac to the behaviour table;    }  } \caption{Detection algorithm.} \end{algorithm}  \end{document}
92806
I see on Stack Overflow and  that the recommendation is to use spaces only for indentation in Python programs.  I can understand the need for consistent indentation and I have felt that pain.  Is there an underlying reason for spaces to be preferred?  I would have thought that tabs were far easier to work with.
18416
I was running a Python script that malfunctioned and used sudo to create a file named &gt;.  How can I get rid of this file?  Of course, when I try sudo rm &gt;, I get the error bash: syntax error near unexpected token 'newline', because it thinks I'm trying to redirect the output of rm.  Its permissions are -rw-r--r--.
2897
Today, I was caught redhanded while attempting to code golf a password generator for Twitter.  import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))   90 chars. Since that is a lot of spare space, I decided to raise the bar and make it executable too.  echo -e "#!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg   139 chars. Nice, except obviously bash chokes on the exclamation point.  badp@delta:~$ echo -e "#!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg bash: !/usr/bin/python\nimport: event not found   Pesky exclamation point. "Let's escape it," I thought! I do have one spare character after all.  echo -e "#\!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg   Obviously...  badp@delta:~$ echo -e "#\!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))"&gt;pg;chmod +x pg;./pg ./pg: line 2: syntax error near unexpected token `(' ./pg: line 2: `import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))' badp@delta:~$ cat pg #\!/usr/bin/python import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))   Leaving my asinine code golfing aside -- I can't explain this.  With \!, the exclamation point was escaped, except it really wasn't, because the \! was left as-is for echo to pick up.  One solution could have been using \x21 instead, but I'm not convinced that's the proper way of escaping an exclamation point in a bash command.  tl;dr: How do you properly escape an exclamation point in a bash command?
56187
I've got multiple-line text files of (sometimes) tab-delimited data.  I'd like to output the file so I can glance over it - so I'd like to only see the first 80 characters of each line (I designed the text file to put the important stuff first on each line).  I'd thought I could use cat to read each line of the file, and send each line to the next command in a pipe:  cat tabfile | cut -c -80   But that seemed broken.  I tried monkeying around, and grep appeared to work - but then I found out that, no it didn't (not every line in the file had 80+ characters) - it appears tabs are counted as single characters by cut.  I tried:  cat tabfile | tr \t \040 | cut -c -80   Even though that would mangle my data a bit, by eliminating the white-space readability.  But that didn't work.  Neither did:  cat tabfile | tr \011 \040 | cut -c -80   Maybe I'm using tr wrong?  I've had trouble with tr before, wanting to remove multiple spaces (appears the version of tr that I have access to on this machine has an -s option for squeezing down multiple characters - I may need to play with it more)  I'm sure if I messed around I could use perl, awk or sed, or something to do this.  However, I'd like a solution that uses (POSIX?) regular commands, so that it's as portable as possible.  If I do end up using tr, I'd probably eventually try turning tabs into characters, maybe do a calculation, cut on the calculation, and then turn those characters back into tabs for the output.  It doesn't need to be a single line / entered directly on the command line - a script is fine.    More info on tab-files:  I use tab to break fields, because someday I may want to import data into some other program.  So I tend to have only one tab between pieces of content.  But I also use tabs to align things with vertical columns, to aid in readability when looking at the plain text file.  Which means for some pieces of text I pad the end of the content with spaces until I get to where the tab will work in lining up the next field with the ones above and below it.   DarkTurquoise           #00CED1         Seas, Skies, Rowboats   Nature MediumSpringGreen       #00FA9A         Useful for trees        Magic   Lime                    #00FF00         Only for use on spring chickens and fru$
108395
All I wrote in the interpreter was as follows:  &gt;&gt;&gt; print "Hello, World!"   File "&lt;stdin&gt;", line 1     print "Hello, World!"                         ^ SyntaxError: invalid syntax   How did I even get an error? All I tried to do was run a print command.
93051
I have a long equation in LaTeX, which I need to break up into more lines. I've done this, although its not quite what I was looking for. Here is a MWE showing my problem:  \documentclass[10pt]{article}  \usepackage[T1]{fontenc} \usepackage{amsmath, amsthm, amssymb} \usepackage[ansinew]{inputenc}  \begin{document} \begin{equation}   \begin{aligned}         \alpha &amp;= 1 &amp;&amp;+ 2     \\                &amp;    &amp;&amp;- 3 + 4 \\                &amp;= 4 \\                &amp;=5-1,   \end{aligned} \end{equation} \end{document}   So there is a long equation broken into 2 lines, followed by 2 short lines. Here is what I desire:   There should be an equation label for each equality sign, so 3 in total. At the moment there is only one The "+2" and "-3+4"-parts are aligned right, which distorts the whole equation. I'm not quite sure why it is doing that, I haven't told it explicitly to do so.   Is there a way to correct these errors?    EDIT: Original output looks like
50285
Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?  Maybe like myString[2:end]?  If leaving the second part means 'till the end', and if you leave the first part, does it start from the start?
43330
In python, if I say  print 'h'   I get the letter h and a newline.  If I say   print 'h',   I get the letter h and no newline.  If I say  print 'h', print 'm',   I get the letter h, a space, and the letter m.  How can I prevent Python from printing the space?  The print statements are different iterations of the same loop so I can't just use the + operator.
106949
I'd love some other opinions on what's more efficient in this code. Basically in the following code, there's a setInterval loop and I need 4 requirements to be true before the code runs in the loop. So in v.1 I wrote an if statement checking all 4. Worked fine.  Then I switched to just using try/catch, with the code I want to execute sitting in try{}. The logic was that during each loop, an exception would be generated but suppressed for each invalid condition. On the final loop where all conditions are true, the code executes and clears the interval.  Either works. I like the try/catch method because there's less conditional code that I need to write and worry about breaking. But I'm worried that try/catch is really inefficient, especially in a setInterval() loop hitting at 100ms. What are some opinions of other bright minds here on SO?  Try/Catch  var intvar = setInterval(function(){ try{         clearInterval(intvar);      jQuery('#'+nav[pageid].t1+'&gt;a').replaceWith(jQuery('&lt;span&gt;'+jQuery('#'+nav[pageid].t1+'&gt;a').text()+'&lt;/span&gt;'));      //set display classes for nav     jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav     jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav }catch(err){} },100);   IF Block  var intvar = setInterval(function(){  if(typeof jQuery == 'function' &amp;&amp; typeof nav == 'object' &amp;&amp; typeof pageid != 'undefined' &amp;&amp; typeof document.getElementById('leftnav') == 'object'){     clearInterval(intvar);     jQuery('#'+nav[pageid].t1+'&gt;a').replaceWith(jQuery('&lt;span&gt;'+jQuery('#'+nav[pageid].t1+'&gt;a').text()+'&lt;/span&gt;'));      //set display classes for nav     jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav     jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav }  },100);
78827
My brother recently started learning C++. He told me a problem he encountered while trying to validate input in a simple program. He had a text menu where the user entered an integer choice, if they entered an invalid choice, they would be asked to enter it again (do while loop). However, if the user entered a string instead of an int, the code would break. I read various questions on stackoverflow and told him to rewrite his code along the lines of:    #include&lt;iostream&gt; using namespace std;  int main() {     int a;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }     }while(true);     return 0; }   While this worked ok, I also tried a few other ideas: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input. 2. I tried if(! cin){//Do Something} which didn't work either. I haven't yet figured this one out. 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function? 4. If write a class that uses cin, but dynamically does this kind of error detection, perhaps by determining the type of the input variable at runtime, would it have too much overhead? Is it even possible?  I would like to know what is the best way to do this kind of checking, what are the best practices?  I would like to add that while I am not new to writing C++ code, I am new to writing good standards compliant code. I am trying to unlearn bad practices and learn the right ones. I would be much obliged if answerers give a detailed explanation.  EDIT: I see that litb has answered one of my previous edits. I'll post that code here for reference.  #include&lt;iostream&gt; using namespace std;  int main() {     int a;     bool inputCompletionFlag = true;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }         else         {             inputCompletionFlag = false;         }     }while(!inputCompletionFlag);     return 0; }   This code fails on input like "1asdsdf". I didn't know how to fix it but litb has posted a great answer. :)
109876
In , the votes clearly show that the os.path.splitext function is preferred over the simple .split('.')[-1] string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?  EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
3114
I'd like to do it in Python. What I'd like to do in this example in C: #include &lt;stdio.h&gt;  int main() {     int i;     for (i=0; i&lt;10; i++) printf(&quot;.&quot;);     return 0; }  Output: ..........  In Python: &gt;&gt;&gt; for i in range(10): print('.') . . . . . . . . . . &gt;&gt;&gt; print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.') . . . . . . . . . .  In Python print will add a \n or space, how can I avoid that? Now, it's just an example, don't tell me I can first build a string then print it. I'd like to know how to &quot;append&quot; strings to stdout.