0

I'm doing code conversion form C to python... I have a char array and is used as a String buffer

 char str[25]; int i=0;

 str[i]='\0';

Here i will be taking different values and even str[i] also holds different values

I want the equivalent code in python... Like a string buffer, where i can store n edit string contents inside. I even tried using a list but it is not very efficient so is there any other way out?? Is there any string buffer thing in Python? If so how can i use it according to these?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Puneeth P
  • 155
  • 4
  • 18
  • `str[i] = '\0';` is not possible in python as strings are immutable object in Python. Also remmember `str` is a type in Python – Grijesh Chauhan Oct 28 '13 at 15:08
  • @GrijeshChauhan: Ya i know that, so is there no other way?? – Puneeth P Oct 28 '13 at 15:09
  • 3
    "I even tried using a list but it is not very efficient" How did you determine this? – Eric Finn Oct 28 '13 at 15:13
  • @Puneeth Mark suggested `bytearray` array I have no idea, search for Read also [Mutable strings in Python](http://stackoverflow.com/questions/10572624/mutable-strings-in-python) look at `MutableString` class – Grijesh Chauhan Oct 28 '13 at 15:13

1 Answers1

1

Use a bytearray to store a mutable list of byte data in Python:

s = bytearray(b'My string')
print(s)
s[3] = ord('f')  # bytes are data not characters, so get byte value
print(s)
print(s.decode('ascii')) # To display as string

Output:

bytearray(b'My string')
bytearray(b'My ftring')
My ftring

If you need to mutate Unicode string data, then list is the way to go:

s = list('My string')
s[3] = 'f'
print(''.join(s))

Output:

My ftring
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251