【问题标题】:Python Checking a string's first and last characterPython检查字符串的第一个和最后一个字符
【发布时间】:2013-11-26 02:27:12
【问题描述】:

谁能解释一下这段代码有什么问题?

str1='"xxx"'
print str1
if str1[:1].startswith('"'):
    if str1[:-1].endswith('"'):
        print "hi"
    else:
        print "condition fails"
else:
    print "bye"   

我得到的输出是:

Condition fails

但我希望它改为打印hi

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    当您说[:-1] 时,您正在剥离最后一个元素。您可以像这样在字符串对象本身上应用startswithendswith,而不是对字符串进行切片

    if str1.startswith('"') and str1.endswith('"'):
    

    于是整个程序就变成了这样

    >>> str1 = '"xxx"'
    >>> if str1.startswith('"') and str1.endswith('"'):
    ...     print "hi"
    >>> else:
    ...     print "condition fails"
    ...
    hi
    

    更简单,用条件表达式,像这样

    >>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
    hi
    

    【讨论】:

      【解决方案2】:

      你应该使用

      if str1[0] == '"' and str1[-1] == '"'
      

      if str1.startswith('"') and str1.endswith('"')
      

      但不要切片并检查startswith/endswith,否则你会切掉你正在寻找的东西......

      【讨论】:

      • 您不小心使用 = 而不是 ==。
      【解决方案3】:

      您正在测试字符串减去最后一个字符

      >>> '"xxx"'[:-1]
      '"xxx'
      

      注意最后一个字符 " 不是切片输出的一部分。

      我认为您只想针对最后一个字符进行测试;使用[-1:] 仅对最后一个元素进行切片。

      但是,这里不需要切片;只需直接使用str.startswith()str.endswith()

      【讨论】:

        【解决方案4】:

        当你设置一个字符串变量时,它不会保存它的引号,它们是它定义的一部分。 所以你不需要使用 :1

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-30
          • 1970-01-01
          • 1970-01-01
          • 2011-04-11
          • 1970-01-01
          相关资源
          最近更新 更多