【问题标题】:String manupulation in python [closed]python中的字符串操作[关闭]
【发布时间】:2016-06-12 15:52:04
【问题描述】:

我有一个代码,其中变量strp 包含string

strp = "HELLO WORLD . I AM NEW TO PYTHON"

我想得到输出为

HELLO WORLD 仅当print strp

应该执行什么字符串操作操作来实现这一点?

我正在使用 python 2.7

【问题讨论】:

  • print strp 将只打印strp 的内容。您只需更改strp 即可获得您要打印的内容。
  • 当您只想要字符串的一部分时会想到哪些字符串操作?请尝试研究这些并在自己周围进行实验。

标签: python string python-2.7


【解决方案1】:

这个?

print strp.split('.')[0]

split上标点并获取第一项

【讨论】:

    【解决方案2】:

    首先你在strp 中找到.,然后在它之前打印strp 的子字符串:

    strp = "HELLO WORLD . I AM NEW TO PYTHON"
    
    period_location = strp.find(".")
    print(strp[:period_location])
    

    【讨论】:

      【解决方案3】:

      使用split

      strp.split(' . ')[0]
      Out[51]: 'HELLO WORLD'
      

      直接索引:

      strp[:11]
      Out[52]: 'HELLO WORLD'
      

      或者使用re:

      import re
      re.split('[.\s]\s*', strp)
      Out[55]: ['HELLO', 'WORLD', '', 'I', 'AM', 'NEW', 'TO', 'PYTHON']
      ' '.join(re.split('\s*[.\s]\s*', strp)[0:2])
      Out[58]: 'HELLO WORLD'
      

      【讨论】:

        【解决方案4】:

        你不能,因为 print strp 会打印 strp 的内容。您可以只打印变量的一部分,例如,使用

        print strp[0:11]
        

        【讨论】:

          猜你喜欢
          • 2012-09-27
          • 1970-01-01
          • 2016-06-29
          • 2019-03-25
          • 1970-01-01
          • 2021-12-07
          • 2016-04-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多