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 o开发者_JAVA百科f the numbers can be different. i know that it has some thing to do with the * and the -
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:])
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:]
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',
精彩评论