views:

89

answers:

3

say i have the following data in a .dat file:

*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5

how can i print the these data like this?:

A : 1 2 3 4

B : 8 2 4

C : 4 2 5 1 5

randomly print any one number for each letter. A, B and C can be any word. and the amount of the numbers can be different. i know that it has some thing to do with the * and the -

+4  A: 

Read in the file, then split() the characters:

contents = open("file.dat").read()
for line in contents.split("*"):
  if not line: continue  # Remove initial empty string.
  line = line.strip()   # Remove whitespace from beginning/end of lines.
  items = line.split("-")
  print items[0], ":", " ".join(items[1:])
Stephen
@Stephen, `items[1:].join(" ")` is a bug -- you need `' '.join(items[1:])` instead (I guess upvoters don't care about such miniscule details as to whether the code they're upvoting _works_;-).
Alex Martelli
what if to get the letters printed separate individually?
babikar
like ,print letter_a, print letter_b , print letter_c
babikar
@Alex : Thanks, fixed. About the upvotes, i think it's because not all of us have interpreters in our heads. :)
Stephen
@babikar : i don't understand what you mean.
Stephen
what am i have to do if i want to like print A somewhere and B some where else same with C not after in each other
babikar
and how can i put the numbers in a list?
babikar
@babikar : about printing, that's gonna depend on hoe you want it printed. to create a list of numbers: `num_list = items[1:]`
Stephen
i want to put them in to a list so that i can print them separately
babikar
@babikar : Create a list before the for loop: `letters = []`, then append each letter within the loop: `letters.append(item[0])`.
Stephen
say i have an output of this, i think its a list['', 'AB-a-b-c-d', 'BC-f-c-a-r', 'CD-i-s-r']i want to make the following:['',[AB,a,b,c,d],[BC,f,c,a,r],[CD,i,s,r]]
babikar
@babikar - you need to split the original list elements on '-'. `'AB-a-b-c-d'.split('-')` -> `[AB,a,b,c,d]`
Stephen
+1  A: 

Also another option

line = "*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5"
s = filter(bool, line.split("*"))
for i in s:
    i = i.split("-")
    print i[0], ":", i[1:]
razpeitia
A: 

Use .split()

data_string = '*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5' #read in the data

data = data_string.split('*') #split the data at the '*'

for entry in data:
    items = entry.split('-')  #split data entries at the '-'
    letter = items[0]         #you know that the first item is a letter
    if not items[0]: continue #exclude the empty string
    print letter, ':',
    for num in items[1:]:
        print int(num),
    print '\n',
Kit