【问题标题】:Python check last word/number in a string?Python检查字符串中的最后一个单词/数字?
【发布时间】:2013-11-12 21:53:15
【问题描述】:

有没有办法让 python 检查/打印字符串中的最后一个单词/数字?

这是我目前所获得的一个示例:

x = input("Input what you want to do to your number and your number: ")
if word.startswith("Pi"):
    Pi_A = x * Pi # I need x to look at the number
    print (Pi_A)

我只需要查看最后一个单词/数字,就可以算出总和。

编辑(输入/输出):

输入:(“Pi 2”是用户输入的内容)

输入你想对你的号码和你的号码做什么:Pi 2

输出:(π * 2 的答案)

6.2...

【问题讨论】:

  • 贴一个输入/输出的例子
  • 在该代码中,word 未定义。剩下的代码是什么?

标签: python string python-3.x


【解决方案1】:

最明显的解决方案是str.endswith

>>> "x * Pi".endswith("Pi")
True

但是,如果不是单独的单词,这也会返回 true:

>>> "PiPi".endswith("Pi")
True

因此,如果您想要以空格分隔的字符串中的最后一个单词,则可以使用

>>> "x * Pi".split()[-1] == "Pi"
True
>>> "PiPi".split()[-1] == "Pi"
False

【讨论】:

    【解决方案2】:

    您可以使用rsplit 来获得最后一个字。然后检查最后一个单词是否以Pi开头

    word = text.rsplit(None, 1)[1]
    if word.startswith("Pi"):
        print (x * Pi) # there is more this is just a example
    

    【讨论】:

      【解决方案3】:

      假设你的字符串是“hello2014bye2013”​​:

      下面的代码应该可以完成这项工作:

      word = "hello2014bye2013"
      alist = list(word)
      print (alist[-1])
      

      如果您有很多单词和数字,那么这应该可以:

      blabla = "hello 4 my 8 name 911 is 049 Python"
      lastword= blabla.split()[-1]
      print (blabla)
      

      【讨论】:

      • @AshishNitinPatil 我刚刚添加了那部分。请再次查看:)
      • 这可能会完成这项工作。 :)
      【解决方案4】:

      这就是你要找的东西

      import math
      x = raw_input("Input action to be peformed on your number, followed by your number: ")
      # Assume "Pi 2"  is entered
      x = x.split()
      action = x[0]
      number = int(x[1])
      if action.startswith("Pi"):
          print number * math.pi
      

      执行

      $ python j.py 
      Input action to be peformed on your number, followed by your number: Pi 2
      6.28318530718
      

      建议:使用“raw_input”而不是“input”来保存引号(也让你为 Python 3.0 做好准备;)

      【讨论】:

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