I'm having a variable which holds the contents that is somewhat similar to this
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
Main_data1;a;b;c;dss;e;1
Main_data2;aa;bb;sdc;d;e;2
Main_data3;aaa;bbb;ccce;d;e;3
Main_data4;aaaa;bbbb;cc;d;e;4
Main_data5;aaaaa;bbbbb;cccc;d;e;5
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
**** SOME JUNK DATA ****
I want to read data that starts with Main_data1.{ Read only the last column and store it into a list} . Please note that this is a variable that holds this data and this is not a file.
My Desired Output:
Some_list=[1,2,3,4,5]
I thought of using something like this.
for line in var_a.splitlines():
if Main_data1 in line:
print (line)
But there are more than 200 lines from which I need to read the last column. What could be an efficient way of doing this
You can use a list comprehension to store the numbers :
Also note that as a more pyhtonic way you better to use
str.startswith()
method rather thanin
operator. (with regards to this poing that it might happen to one line hasMain_data5
in the middle of the line!)If you have two case for start of the line you can use an
or
operator with twostartswith
consition.But if you have more key-words you can use regex.For example if you want to match all the linse that stats with
Main_data
and followed by a number you can usere.match()
:My approach is regex since it can control over pattern more-
File content
Code
Output
Or you can use the startswith('match)' function like someone mentioned.
Check if line starts with
"Main_data"
than split by semi-colon;
and choose the last element by index-1
: