Guilhermeths
Guilhermeths

Reputation: 13

separating columns CSV in python

how to separate this line, I need just the numbers

PD-1358 393;

I would like to increment a variable X and a Y

 X   Y
PD-1358 393;

I am using the CSV command (csv_file, delimiter='-') but I can not separate these numbers. Can anybody help me?

import csv

with open('circulo.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='-')

    line_count = 0
    for row in csv_reader:

         print(f'\t {row[0]}')

For the moment I've only been able to separate this part

Upvotes: 0

Views: 75

Answers (3)

James Holmes
James Holmes

Reputation: 410

If you want numbers in the final array:

line = 'PD-1358 393;'

parts = line.split(' ')

numbers = [int(''.join(i for i in part if i.isdigit())) for part in parts]

Upvotes: 0

ggrelet
ggrelet

Reputation: 1101

Using regex you can simply do:

import re

re.findall(r'\d+', "PD-1358 393") 

Result:

['1358', '393']

Upvotes: 2

Ishmael
Ishmael

Reputation: 235

Don't know of an easy way to do this, but assuming you've turned the data into a string like so:

s = 'PD-1358 393'

Then create a generator to go to the first instance of a digit:

i = next((index for (index,value) in enumerate(s) if value.isdigit()))

And then split:

s[i:].split()

Returns:

['1358', '393']

Upvotes: 0

Related Questions