top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can I remove the first line of a multi-line string in python

+2 votes
5,074 views

I have a multi-line string and I need to remove the very first line from it. How can I do that? I looked at StringIO but I can't seem to figure out how to properly use it to remove the first line.

posted Sep 2, 2013 by Ahmed Patel

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Use split() and join() methods of strings, along with slicing. Like this:

 fullstring = "foo
 bar
 baz"

 sansfirstline = 'n'.join(fullstring.split('n')[1:])

The last line does this:
1. fullstring.split('n') turns it into a list of ['foo', 'bar', 'baz']
2. the [1:] slice removes the first element, making it ['bar', 'baz']
3. Finally, 'n'.join() turns the list into a string separated by newlines ("bar
baz")

answer Sep 2, 2013 by Mandeep Sehgal
Similar Questions
+1 vote

Here is something I found curious about python loops.

This loop run each character in a string

def avoids(word,letters):
 flag = True
 for letter in letters:
 if(letter in word):
 flag = False
 return flag

The loop below (at the bottom) runs each line of the file

fin = open('wordplay.txt');
user_input = raw_input('Enter some characters: ')
count = 0
for line in fin:
 word = line.strip()
 if(avoids(word, user_input)):
 count += 1;

This is just too convenient. Basically my question is: Why is python not treating the contents of wordplay.txt as one long string and looping each character?

Any comment is greatly appreciate.

+2 votes

I'm trying to search for several strings, which I have in a .txt file line by line, on another file. So the idea is, take input.txt and search for each line in that file in another file, let's call it rules.txt.

So far, I've been able to do this, to search for individual strings:

import re
shakes = open("output.csv", "r")

for line in shakes:
 if re.match("STRING", line):
 print line,

How can I change this to input the strings to be searched from another file?

0 votes

Find the first non repeating character in a string.

For example
Input string: "abcdeabc"
Output: "e"

...