0

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)

Allexj
  • 1,375
  • 6
  • 14
  • 29
  • Strings are immutable, you need to assign `x.strip(" ").split("|")` to some variable. – Ashwini Chaudhary Aug 27 '17 at 17:39
  • print x.replace(" | smth","") – CodeCupboard Aug 27 '17 at 17:41
  • x[0] refers to the first character in the string x, and x is the entire line. split() returns a result, which you're not assigning to anything. You need to assign the result to y, then y[0] will refer to the first element in the array for that line. – Mike Aug 27 '17 at 17:46

2 Answers2

1

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])
Elisha
  • 23,310
  • 6
  • 60
  • 75
1

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)

Lloyd Jackman
  • 156
  • 1
  • 6