将字符串分成两个Python数组

时间:2016-04-26 15:56:05

标签: python

我正在尝试使用下面的查询将一串单词分成两个单词列表。直到'a'的字符串应该开始,剩下的字符串应该是剩余的。但是while循环以某种方式继续运行,而不管start已经包含'a'的事实。非常感谢你的帮助!

random_string = 'hello this is a test string'
split = {}
split = random_string.split()
begin = []
remainder = []

while 'a' not in begin:
for word in split:
    storage = word
    begin.append(storage)


print(begin)

6 个答案:

答案 0 :(得分:1)

所以你的问题是在for循环完成后检查while循环条件。基本上这就是发生的事情

  1. '一个'尚未开始
  2. 循环分割并添加每个单词以开始
  3. 检查是' a'正在开始
  4. 您可以尝试以下方式:

    for word in split:
        if 'a' in begin:
            remainder.append(word)
        else:
            begin.append(word)
    

    其中' a'在循环的每次迭代中检查条件或遵循其他答案中列出的切片技术

答案 1 :(得分:0)

试试这个,只需两行。一个用' a'得到单词,另一个得到单词而不用' a'。

random_string = 'hello this is a test string, tap task'

begin = [x for x in random_string.split(' ') if 'a' in x]
remainder = [x for x in random_string.split(' ') if 'a' not in x]

print begin, remainder

将打印。

['a', 'tap', 'task']
['hello', 'this', 'is', 'test', 'string,']

答案 2 :(得分:0)

尝试使用切片和索引,不需要运行循环来捕获' a':

random_string = 'hello this is a test string'
split = random_string.split(' ')
index = split.index('a') + 1
array_1 = split[:index]
array_2 = split[index:]

print(array_1, array_2)

答案 3 :(得分:0)

通过拆分字符串,只需slice列表:

将句子取为特定单词:

>>>words = "one two three four"
>>>words.split()[:words.split().index("three")+1]
['one', 'two', 'three']
>>>words.split()[words.split().index("three")+1:]
['four']

取一半的句子:

(你的帖子似乎对我想要的东西含糊不清。)

>>>words = "one two three four"
>>>words.split()[:len(words.split())//2]
['one', 'two']
>>>words.split()[len(words.split())//2:]
['three', 'four']

答案 4 :(得分:0)

您应该查看.index数组方法,而不需要循环。

random_string = 'hello this is a test string'

split = random_string.split()

begin = []
remainder = []
index = split.index('a')

begin = split[:index] 
remainder = split[index:]

print(begin)
print(remainder)

上面的代码段将打印:

['hello', 'this', 'is']
['a', 'test', 'string']

答案 5 :(得分:-2)

使用内置字符串例程:

>>> str = 'hello this is a test string'
>>> begin, end str.split('a')
['hello this is ', ' test string']
>>> begin_words = begin.split()
['hello', 'this', 'is']
>>> end_words = end.split()
['test', 'string']

split的默认值是在空格上拆分,但正如您所看到的,它也适用于其他字符串。