0

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 -

2
  • what if I want to randomly print only one of the numbers? Commented Jul 9, 2010 at 3:25
  • import random, then help(random). It's easy, but we've already done enough of your homework :) Commented Jul 9, 2010 at 3:31

3 Answers 3

4

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:])
Sign up to request clarification or add additional context in comments.

12 Comments

@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;-).
what if to get the letters printed separate individually?
like ,print letter_a, print letter_b , print letter_c
@Alex : Thanks, fixed. About the upvotes, i think it's because not all of us have interpreters in our heads. :)
@babikar : i don't understand what you mean.
|
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:]

Comments

0

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',

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.