1

Hey I'm currently using python to read a list of string in a txt file and I wanted to cut off multiple strings in the front e.g

example in my txt file:

Jack: Black

Jack: Sparrow

Jimm: Oliver

Jimm: Next

Jimm: Red

Ston: Cold

Bill: Black

I wanted to remove the first 5 string (including ':') from each line so the desired result might be

Black

Sparrow

Oliver

Next

Red

Cold

Black

I've been trying using .replace() but I cannot determine the string neither using string slicing (it will cut only the few characters in the first line)

currently my program looks like this:

with open("C:\\Documents and Settings\\Zha\\Desktop\\test3.txt", "r") as text:
    a = text.read()
    b = str(a).replace(a[:5],'')
    print b

and the current output is

 Black

 Sparrow

Jimm: Oliver

Jimm: Next

Jimm: Red

Ston: Cold

Bill: Black
1
  • Might I also add: awk test3.txt '{print $2}' Commented May 21, 2014 at 8:34

4 Answers 4

2

Iterate over each line in the file:

with open(filename, "r") as text:
    for line in text:
        print line[6:]
Sign up to request clarification or add additional context in comments.

Comments

1

Use split:

with open("C:\\Documents and Settings\\Zha\\Desktop\\test3.txt", "r") as text:
    for line in text:
        if line.strip():
            print line.split(':')[1].strip()

Comments

1

a is the whole of the file, as a string:

"Jack: Black\nJack: Sparrow\nJimm: Oliver\n" # and so on

so a[:5] == 'Jack:', which you duly replace all occurrences of, but this doesn't do anything with the lines that don't include those characters.

For what you are trying to achieve, readlines() (which gives a list where each item is one line as a string) in combination with split is probably more use:

b = [line.split()[1] for line in text.readlines()]

i.e. "for each line in the file, split on whitespace and give me the second part". This gives b == ["Black", "Sparrow", "Oliver", ...] and means you aren't limited to lines where the first part is exactly 5 characters.

Comments

0

You can do it with the following code:

with open('input.txt') as f:
  f = f.readlines()

f = [i[6:].strip() for i in f]

print f

[OUTPUT]
['Black', 'Sparrow', 'Oliver', 'Next', 'Red', 'Cold', 'Black']

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.