Strings are immutable objects in python: cannot be modified in-place. If you want to modify it, you have to create new string objects.

I want to modify string in-place sometimes, though. What should I do?

io.StringIO

1
2
3
4
5
6
7
8
import io

s = 'best_creature_lei'
s_io = io.StringIO(s)
print(s_io.getvalue()) # Using IO, get new string value: "best_creature_lei"
s_io.seek(14) # pointer moves to index 14
s_io.write("雷")
print(s_io.getvalue()) # new value: "best_creature_雷ei"

in dev

There is a dataframe called actual, I want to read this dataframe, modify in-place and write it back without the extra column Unnamed:0.

Here is the raw dataframe actual.

  1. read from it without 1st column:

    1
    2
    3
    4
    5
    import pandas as pd
    csv = io.StringIO()
    actual.to_csv(csv)
    csv.seek(0)
    actual = pd.read_csv(csv, index_col=0) # rid Unnamed:0
  2. Or even more efficiently, write into stream without 1st column

    1
    actual = pd.read_csv(io.StringIO(actual.to_csv(index=False))

For more information about get rid of Unnamed:0 in pandas, click here

irrelevant: (Java: StringBuilder is not thread-safe, StringBuffer is thread-safe)