2

I want to split string between a tab. Let's say I have some text in a file.txt

Kern_County_Museum  1,000,000+
Fairplex_railway_exhibit    Depot and rolling stock

So I want to remove redundancy from left side and keep right side as it is.

import re
import string
import urllib

for line in open('file.txt', 'r').readlines():
left, right = string.split(line, maxsplit=1)
relation = string.split(line, maxsplit=1)

le = relation[0]
ri = relation[1]

le = urllib.unquote(relation[0])
le = le.replace('_', ' ')


print le, '\t', ri
1
  • 2
    You should not use string.split(). Each string object provide the split() method directly. Commented Jul 14, 2011 at 10:17

3 Answers 3

2

Restrain your split.

left, right = line.split(None, 1)
Sign up to request clarification or add additional context in comments.

Comments

1

By default split method splits string by any whitespace. To split string by a tab, pass extra parameter to this method:

left, right = line.split('\t', 1)

5 Comments

I thought they split by whitespace, rather than " "
@samb8s well, yes, by any white-space.
@Roman Bodnarchuk: Please give details.Still getting error need more than 1 values to unpack
@Roman Bodnarchuk: questions updated.Also, tried with your updated, still getting error.
@Blue it looks like you are still using your original version of split.
0

Use str.partition

left, delim, right = line.partition('\t')

1 Comment

@Blue Ice, if you're using Python older than 2.5, it's a good idea to mention it in the question/tags

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.