来自python中字符串的子字符串

时间:2015-03-18 10:36:35

标签: python

我是python的新手,我有一个基本的问题要做。

我有一个字符串,我想得到它的一些部分并将它们存储为单独的字符串。

我的字符串看起来像这样: label = "1000 likes 200 comments 150 shares"

我想要的是这样的3个字符串: likes = 1000
comments = 200 shares = 150

提前谢谢大家

5 个答案:

答案 0 :(得分:3)

您可以使用re.findall功能。

>>> label = "1000 likes 200 comments 150 shares"
>>> likes,comments,shares = re.findall(r'\d+(?=\s+(?:likes|comments|shares)\b)', label)
>>> likes
'1000'
>>> comments
'200'
>>> shares
'150'

答案 1 :(得分:1)

您可以使用以下单词拆分字符串:

values[] = label.split()

创建的变量值如下所示:

["1000","likes","200","comments","150","shares"]

然后创建像这样的变量like,comments和shares:

likes = values[0]
comments = values[2]
shares = values[4]

这将使用字符串中的数字填充变量。有关详细信息,请参阅str.split()

答案 2 :(得分:0)

如果您想要子字符串,并且标签字符串的长度始终相同并且保持相同的结构,您可以执行以下操作:

label =  "1000 likes 200 comments 150 shares"
likes_str = label[:10]
comments_str = label[11:23]
shares_str = label[24:]

print likes_str
print comments_str
print shares_str

输出:

1000 likes
200 comments
150 shares

基本上:
[:10]从开始到char 10
[11:23]从char 11到23
[24:]从char 24到结束

检查上一个stackoverflow问题以及此字符串上的tutorial

答案 3 :(得分:0)

如果你想提取字符串的一部分,你可以用一种非常基本的方式来获取每个字符的位置。

因此,如果您知道要提取的位置,则可以创建仅获取所需字符的新字符串。

您可以索引字符串并执行类似的操作:

label = "1000 likes 200 comments 150 shares"
#Likes gets from character in the position 0 until the character in the position 3
likes = label[0:4]
#comments gets from character in the position 11 until the character in the position 13
comments = label[11:14]
#shares gets from character in the position 24 until the character in the position 26
shares =  label[24:27]

之后你有三个字符串

答案 4 :(得分:0)

如果你不确切知道字符串中的项目(对于Python 3.3),你可能想要一个更通用的解决方案:

# import regular expressions module
import re
label = "1000 likes 200 comments 150 shares 4 edits"
# split all words in your string
labelList = re.split('\s+', label)
# count quantity of items in your string
quantOfItems = int(len(labelList) / 2)
# iterate all items from 0 to quantOfItems
for i in range(quantOfItems):
    # output the result
    print('%s = %s' % (labelList[i*2+1], labelList[i*2]))