擅长:python、mysql、java
<p>当你说<code>[:-1]</code>时,你是在剥离最后一个元素。您可以对字符串对象本身应用<code>startswith</code>和<code>endswith</code>,而不是对字符串进行切片,如下所示</p>
<pre><code>if str1.startswith('"') and str1.endswith('"'):
</code></pre>
<p>所以整个程序变成这样</p>
<pre><code>>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
... print "hi"
>>> else:
... print "condition fails"
...
hi
</code></pre>
<p>更简单的是,使用条件表达式,比如</p>
<pre><code>>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi
</code></pre>