1

I have a file, each line looks like this:

#each line is a list: 
a = ['1\t2\t3\t4\t5']
#type(a) is list
#str(a) shows as below:
["['1\\t2\\t3\\t4\\t5']"]

I want an output of only 1 2 3 4 5, how should I accomplish that? Thanks everyone.

9
  • [i.replace('\t',' ') for i in a]? Commented Jul 31, 2015 at 18:48
  • ast.literal_eval()? Commented Jul 31, 2015 at 18:48
  • I think I solved this one by using list(str(a)[2:-2].split('\\t')) but this seems over complicated the problem. Commented Jul 31, 2015 at 18:53
  • I'm still not clear on the actual appearance of the line in the file, or the object or data structure you want to end up with. Commented Jul 31, 2015 at 19:01
  • @TigerhawkT3 I'm trying to get a list eventually, then count how many 1,2,3,4,5 is there in the whole file. Commented Jul 31, 2015 at 21:16

3 Answers 3

3

I agree with Bhargav Rao. Use a for loop.

for i in a:    
    i.replace('\t',' ') 
    print i

I believe it will print out the way you want. Otherwise please specify.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are reading lines from a file, you can use the following approach:

with open("file.txt", "r") as f_input:
    for line in f_input:
        print line.replace("\t"," "),

If the file you are reading from is actually columns of data, then the following approach might be suitable:

import csv

with open("file.txt", "r") as f_input:
    csv_input = csv.reader(f_input, delimiter="\t")

    for cols in csv_input:
        print " ".join(cols)

cols would give you a list of columns for each row in the file, i.e. cols[0] would be the first column. You can then easily print them out with spaces as shown.

1 Comment

Hi Martin, thanks for your reply, you are right about the delimiter, I complicated the whole thing by putting delimiter as ',' thinking that it's a csv file must be comma delimited, but in fact it is '\t' delimited, so now everything solved.
0

there are many ways of doing this. you can use a for loop or you can just join the list and replace all the \t

a = ['1\t2\t3\t4\t5']

a = "".join(a).replace("\t", "")
print(a)

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.