【问题标题】:cutting a string at spaces python在空格处切割字符串python
【发布时间】:2015-09-08 07:46:13
【问题描述】:

我开始学习python并想在空格处剪切一个字符串;所以'hello world'变成'hello'和'world'。为此,我想将空格的位置保存在列表中,但我不知道该怎么做。为了找到空间,我这样做:

    def string_splitting(text):
        i = 0
        for i in range(len(text)):
            if (text[i]==' '):

将它们保存在列表中后,我想用 text[:list[1]](或类似的东西)显示它们

谁能帮我把它保存在列表部分;这甚至可能吗?

(欢迎使用另一种截断字符串的方法:-))

谢谢。

【问题讨论】:

    标签: string python-2.7 spaces


    【解决方案1】:

    使用拆分:

    "hello world my name is".split(' ')
    

    它会给你一个字符串列表

    【讨论】:

      【解决方案2】:

      谢谢,我尝试在没有拆分选项的情况下这样做,应该在问题中这么说..

      无论如何这都有效;

          def split_stringj(text):
              a = text.count(' ')
              p = len(text)
              l = [-1]
              x = 0
              y = 1
              for x in range(p):
                  if (text[x]==' '):
                      l.append(x)
                      y += 1
              l.append(p)
              print l
              for x in range(len(l)-1):
                  print text[l[x]+1:l[x+1]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-14
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        • 2012-09-22
        • 1970-01-01
        • 2020-05-16
        相关资源
        最近更新 更多