EnigmaticDev
EnigmaticDev

Reputation: 15

How to remove characters from a string after a certain point within a list?

I have a list of strings within a list and I want to remove everything in each string after the tenth character.

EX:

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

I want just the first ten integers from the list and everything else should be stripped from it.

Output

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

Upvotes: 0

Views: 959

Answers (4)

dsb4k8
dsb4k8

Reputation: 61

Split() creates a list of strings delimited by the specified character. With this in mind, I would split each string on the comma (,) char and then append the first element to a list.

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)

This should return the values you need, in the format you want! Hope this helps.

Upvotes: 0

yang5
yang5

Reputation: 1235

list comprehension and string slicing:

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]

Upvotes: 0

iz_
iz_

Reputation: 16593

You can use a list comprehension:

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]

Output:

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

You can also be a bit more flexible if you want to keep everything before the first comma:

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

Upvotes: 1

J.D.
J.D.

Reputation: 4561

You can access string characters similar as an array.

Code:

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])

Output:

0.04112243
0.12733313
0.09203131

Upvotes: 0

Related Questions