Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i remove the first character from a StringIO object?

I couldn't figure it out with the Python documentation, so maybe i can ask it here:

import StringIO
line = StringIO.StringIO()
line.write('Hello World')

Is there any method i can use, that will do what line[1:] would do on a string, so line.getvalue() will return ello World?

Thanks.

like image 667
VCake Avatar asked Jun 21 '13 13:06

VCake


People also ask

How do I remove the first character in Python?

Python provides various inbuilt functions, Slicing() is one of them. If we wish to delete the first character or some other char from the python string, we can erase that character using the slicing method and then get the resultant string excluding the first character.

How do you remove the first part of a string in Python?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.

How do you trim the first and last character in Python?

Alternatively, you can use the str. lstrip() and str. rstrip() methods to remove characters from the start and end of the string.

How do you remove the first n characters from a string in Python?

You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.


2 Answers

I can't figure out how to do it with line.getvalue, but you can use StringIO objects like normal file objects. Just seek to byte 1 and read as you normally would.

>>> import StringIO
>>> line = StringIO.StringIO()
>>> line.write("Hello World")
>>> line.seek(0)
>>> print line.getvalue()
Hello World
>>> line.seek(1)
>>> print line.getvalue()
Hello World
>>> line.seek(1)
>>> print next(line)
ello World
>>> line.seek(1)
>>> print line.read()
ello World
like image 69
mgilson Avatar answered Oct 19 '22 04:10

mgilson


The StringIO getvalue() function return the content as string, so this could be work:

content = line.getvalue()
print content[1:]
like image 30
Cesar Avatar answered Oct 19 '22 02:10

Cesar