keokoefkoek keokoefkoek - 1 year ago 69
Python Question

Removing first character in a String leaves whitespace

I have a textfile that looks like this:

6 Hello World

I'm reading it in as such:

with open("test.txt") as fp:
for line in fp:
l = line.split(" ")

Which prints me the entire string:

6 Hello World

I want to remove the '6' character, and just store the string 'Hello World' in another string:

I've done this

newStr = l.replace(l[0],"")

Which now gives me:

Hello World

Now I want to remove the leading space, and store the string.
I tried this:

newStr2 = newStr.replace(newStr[0],"")

But this prints:


Instead of
Hello World
(no leading space character)
What am I doing wrong here?
Also, using len() on newStr2 tells me the length is 11, even though it's 10. Is len() including a newline character?

Answer Source

That's because newStr.replace(newStr[0],"") is the same as newStr.replace(" ","") which replaces every instance of a single space with an empty string.

What you want is lstrip which removes all leading whitespaces from your string.

More so, to be less verbose, you can simply slice off the leading character from the string and then lstrip:

newStr = l[1:].lstrip()

On another note, a new line character is a character of length one and that is properly accounted for in len:

>>> len('\n')

Pro-Tip: line.split() does the same and is more efficient than line.split(" "). See Why is str.strip() so much faster than str.strip(' ')?

Essentially, your code becomes:

with open("test.txt") as fp:
    for line in fp:
        l = line.split()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download