5

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
VCake
  • 323
  • 1
  • 3
  • 10
  • 1
    You need to **call** `StringIO` to create an instance; `line = StringIO.StringIO()`. `.getvalue()` returns a string, why not slice *that*? – Martijn Pieters Jun 21 '13 at 13:19
  • 1
    And this smells like a [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem); what are you trying to solve, *really*. – Martijn Pieters Jun 21 '13 at 13:19
  • (http://stackoverflow.com/questions/4945548/removing-a-character-from-a-certain-position-in-a-string-in-python/) – Andrew_CS Jun 21 '13 at 13:20
  • Thanks for the editing the typo. I don't want to slice the returned string but instead modify what the StringIO object holds, so further access to it would be sans that first character. My problem is that line[1:] would erase StringIO's methods, i'm interested in only modifying the text that getvalue() would return. – VCake Jun 21 '13 at 13:23

2 Answers2

5

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
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    Thanks! seek() and read() do exactly what i need. Is there a way to make it seek from the next character each time without using an index variable? seek(i), i = i + 1... – VCake Jun 21 '13 at 13:40
  • @VCake -- You can figure out your current position using `tell`. you can seek from the current position by `seek(1,1)` (I think) – mgilson Jun 21 '13 at 13:52
  • @mgilson: Yep, that's correct: https://docs.python.org/3/library/io.html#io.IOBase.seek (the first number is the offset which can be negative, too; the second number indicates the seek-mode, where `1` sets "current stream position" as the "starting point") -- added in Python 3.1 (it does only work for BytesIO, though, and not for StringIO: http://stackoverflow.com/questions/19981996/relative-seek-for-io-stringio-in-python3) – mozzbozz Nov 10 '14 at 13:29
2

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

content = line.getvalue()
print content[1:]
Cesar
  • 707
  • 3
  • 13