如何将字符串从特定字符串拆分为特定字符

时间:2017-05-21 17:29:14

标签: python string split

我想将一个字符串从“#”拆分为“::”,我想多次这样做,这个字符串关于专辑和歌曲,我想分割所有歌曲和专辑的标题:

Input:'the songs is # Moving On:: by Marshmello '#the string
Output:'Moving On'#songs name

我不想对索引这样做,因为标题有所不同 长度以及不同地方的歌曲。

7 个答案:

答案 0 :(得分:1)

我能想到的最简单的方法是:

x = 'the songs is # Moving On:: by Marshmello '
print( x[x.find('# ')+2: x.find('::')] )

答案 1 :(得分:1)

您可以使用正则表达式来实现一个非常小的解决方案......

re.search(r'#\s*(.+)\s*::', 'the songs is # Moving On:: by Marshmello ').group(1)

答案 2 :(得分:0)

试试这个:

str = 'the songs is # Moving On:: by Marshmello'


def find_between( s, first, last ):
   try:
      start = s.index( first ) + len( first )
      end = s.index( last, start )
    return s[start:end]
except ValueError:
    return ""

print find_between(str, "#", "::");

答案 3 :(得分:0)

我会首先分开#,所有人。之后我会在两个不同的数组中拆分::

>>> string = 'the songs is # Moving On:: by Marshmello '
>>> string.split('#',1)[1].split('::',1)[0]
' Moving On'

答案 4 :(得分:0)

那么,你可以做到那一点。您可以多次拆分字符串,如下所示。

"the songs is # Moving On:: by Marshmello".split("#")[1].split("::")[0]

这将为您提供歌曲名称。

答案 5 :(得分:0)

您可以像任何其他列表一样切割字符串:

"Some String"[1:2]

会给你

"om"

你可以得到这样一个特定角色的第一个索引:

"Some String".index("S")

会返回0。

对于您的情况,您可以执行以下操作:

sentence = 'the songs is # Moving On:: by Marshmello '
start_string = "# "
first = sentence.index(start_string) + len(start_string # Add the length of the start string because we want to start the slice at the end of the string 
end_string = "::"
last = sentence.index(end_string)
slice = sentence[first:last]

答案 6 :(得分:0)

试试这个,

import re
song = 'the songs is # Moving On:: by Marshmello'
title = re.findall(r'#(.*?)::', song)
print title[0]
相关问题