Wiktor
Wiktor

Reputation: 631

python - get part of string from query results

I have a small script which download me a results from query and export it to .csv

yy = raw_input("Enter year: ")
mm = raw_input("Enter month: ")

try:

    conn = psycopg2.connect("dbname='xxx' user='xxx' host='xxx' password='xxx'")
    cur=conn.cursor()

 query1 = """SELECT name FROM xxx where name like '%{0}_{1}%' """.format(yy,mm)
        cur.execute(query1)
        results = cur.fetchall()
        for row in results:
        print row

csv_file = open('errors.csv','wb')# wb - query importing line by line
myFile = csv.writer(csv_file)
myFile.writerows(results)
csv_file.close()

What i need is a part of string from query results. Atm my results looks like this:

1-GRB-804_2016_02_03__08_42_12
1-GRB-804_2016_02_05__11_04_47
1-GRB-804_2016_02_06__08_20_15
1-GRB-804_2016_02_08__08_06_13
1-GRB-804_2016_02_08__08_30_58

And what i want is to get first line untill it meet sign '_'. So results will be :

1-GRB-804
1-GRB-804
1-GRB-804
1-GRB-804
1-GRB-804

Regards

Upvotes: 0

Views: 402

Answers (1)

Arcturus B
Arcturus B

Reputation: 5631

You want to keep everything until the first “_”, you can simply use string.split:

>>> s = '1-GRB-804_2016_02_03__08_42_12'
>>> s.split('_')
['1-GRB-804', '2016', '02', '03', '', '08', '42', '12']
>>> s = s.split('_')[0]
>>>> s
'1-GRB-804'

So in your case, you would need to do:

for row in results:
    print row.split('_')[0]

Upvotes: 1

Related Questions