如何在列表中的某个点之后从字符串中删除字符?

时间:2019-02-03 22:24:36

标签: python list

我在列表中有一个字符串列表,我想删除第十个字符之后的每个字符串中的所有内容。

EX:

['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']

我只想要列表中的前十个整数,其他所有内容都应该从中删除。

输出

['0.04112243', '0.12733313', '0.09203131']

4 个答案:

答案 0 :(得分:1)

您可以使用列表理解:

original = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']

new = [s[:10] for s in original]

输出:

['0.04112243', '0.12733313', '0.09203131']

如果您想将所有内容保留在第一个逗号之前,也可以更加灵活一些:

new = [s.partition(',')[0] for s in original]

答案 1 :(得分:0)

您可以访问类似于数组的字符串字符。

代码:

example = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
for s in example:
    print(s[:10])

输出:

0.04112243
0.12733313
0.09203131

答案 2 :(得分:0)

列表理解和字符串切片:

dirty = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']

clean = [num[:10] for num in dirty]

答案 3 :(得分:0)

Split()创建一个由指定字符分隔的字符串列表。考虑到这一点,我将在逗号(,)char上拆分每个字符串,然后将第一个元素附加到列表中。

lst = ['0.04112243,0.04112243,right,4.11%', '0.12733313,0.05733313,right,12.73%', '0.09203131,0.02203131,right,9.2%']
result = []
for i in lst:
    result.append(i.split(",")[0])
#Test output
print(result)

这应该以所需的格式返回所需的值! 希望这会有所帮助。