Blue Ice
Blue Ice

Reputation: 85

string split in python

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

Upvotes: 2

Views: 8796

Answers (3)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

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)

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304147

Use str.partition

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Restrain your split.

left, right = line.split(None, 1)

Upvotes: 2

Related Questions