title: Swap first and last letter of a string in Python
body: <p>I hope I'm missing something obvious here, but I was playing around with the Python CodingBat site, and got to the problem <a href="http://codingbat.com/prob/p153599" rel="nofollow">front_back</a>:</p>
  
  <blockquote>
    <p>For a string passed in, return it with its first and last characters swapped, if the string length is greater than 1.</p>
  </blockquote>
  
  <p>I came up with a single line solution which I thought would suffice but Coding.bat refuses to accept it, with an Index out of range error.</p>
  
  <p>I've played around in IDLE (64bit windows version) and I've boiled the problem down to this:</p>
  
  <pre><code>len(str) &lt; 2 and str or 'doh ' + str + ' /doh'
  </code></pre>
  
  <p>The wierd problem is that setting <code>str = ''</code> returns:</p>
  
  <pre><code>'doh  /doh'
  </code></pre>
  
  <p>Which it shouldn't as len('') is 0, but <code>str='a'</code> returns:</p>
  
  <pre><code>'a'
  </code></pre>
  
  <p>and <code>str='abc'</code> returns:</p>
  
  <pre><code>'doh abc /doh'
  </code></pre>
  
  <p>Which I would expect...</p>
  
  <p>So my question is really; Why is checking the len of '' going to the OR condition of the ternary operator, but running <code>len('')</code> at the console return 0, which is obviously less than 2?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>This solution actually works, however:</p>
  
  <pre><code>  def front_back(str):
      if len(str)  &lt; 2:
          return str
      else:
          return str[-1] + str[1:-1] + str[0]
  </code></pre>
  
  <p>To 'mtadd'; thanks for your answer but this isn't a logical and/or this is a pythonic ternary operator:</p>
  
  <pre><code>return (statement) and &lt;statement was true&gt; or &lt;statement was false&gt;
  </code></pre>
  
  <p>It's the same as C#'s:</p>
  
  <pre><code>return statement
      ? trueValue
      : falseValue;
  </code></pre>