Python – Delete a part of each line of a textfile

Question:

I have a text file like this:

abc123bvjhfvb:dlnvsl|smth
 fsbffsb378hbdcbs:v5v3v|smth
 sdcg87wgn8:vy5b4|smth
 sin87s88vnus:y54545v4v|smth
 rc8n782c:efghrn|smth

As you can see there is a space starting from the second line.

How can I convert these lines to these?

abc123bvjhfvb:dlnvsl
fsbffsb378hbdcbs:v5v3v
sdcg87wgn8:vy5b4
sin87s88vnus:y54545v4v
rc8n782c:efghrn

I tried something like this:

lines = open("file.txt").readlines()

for x in lines:
    x.strip(" ").split("|")
    print (x[0])

But it prints only the “a” of abc123 and then a series of space for each line. I think the [0] goes to print the first letter instead of printing the first part of split before the “|” (for example abc123bvjhfvb:dlnvsl)

Asked By: Allexj

||

Answers:

The issue is that strip and split do not mutate x.

The code needs to use the returned value:

for x in lines:
    x = x.strip(" ").split("|")
    print (x[0])
Answered By: Elisha

You need the [0] at the end of the split bit otherwise you are string indexing, not indexing the parts of the split.

You’d also be good to assign a variable fur the strip and split bit and then print it i.e. y = … print(y)

Answered By: Lloyd Jackman
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.