我不能Python文檔看着辦吧,也許我可以問在這裏:我如何從StringIO對象中刪除第一個字符?
import StringIO
line = StringIO.StringIO()
line.write('Hello World')
有沒有什麼方法,我可以使用,這將做什麼line[1:]
將在一根繩子上做, 這樣line.getvalue()
將返回ello World
?
謝謝。
我不能Python文檔看着辦吧,也許我可以問在這裏:我如何從StringIO對象中刪除第一個字符?
import StringIO
line = StringIO.StringIO()
line.write('Hello World')
有沒有什麼方法,我可以使用,這將做什麼line[1:]
將在一根繩子上做, 這樣line.getvalue()
將返回ello World
?
謝謝。
我不知道如何與line.getvalue
做到這一點,但可以像使用普通文件對象一樣使用StringIO對象。只需尋找字節1並按照通常的方式閱讀即可。
>>> 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
謝謝! seek()和read()正是我所需要的。有沒有一種方法可以讓它在不使用索引變量的情況下每次從下一個字符開始尋找?尋求(i),i = i + 1 ... – VCake
@VCake - 您可以使用tell來確定您當前的位置。你可以通過seek(1,1)'(我認爲) – mgilson
@mgilson找到當前位置:是的,這是正確的:https://docs.python.org/3/library/io.html#io.IOBase .seek(第一個數字也可以是負數的偏移量;第二個數字表示搜索模式,其中'1'將「當前流位置」設置爲「起始點」) - 在Python 3.1中添加不過只適用於BytesIO,而不適用於StringIO:http://stackoverflow.com/questions/19981996/relative-seek-for-io-stringio-in-python3) – mozzbozz
的StringIO的的GetValue()函數返回的內容爲字符串,所以這可能是工作:
content = line.getvalue()
print content[1:]
你需要** **調用'StringIO'創建一個實例; 'line = StringIO.StringIO()'。 '.getvalue()'返回一個字符串,爲什麼不切片*那*? –
這聞起來像[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem);你想要解決什麼問題,*真的*。 –
(http://stackoverflow.com/questions/4945548/removing-a-character-from-a-certain-position-in-a-string-in-python/) –