0

I am working on some code in python, here I want to work on different indexes of a single word. For example, I took input from user in a string. If user enters "Banana" than I cant modify any index of this word say 2nd or 3rd index as it is a string. So my question is how can I convert this string to a list so that I can access and edit each letter of this word? Or is there any method that I take input in list with each letter on each index not complete word on first index?

I have tried str.split() but it just removes spaces between the word whereas I am dealing with a single-word string so split do not works with it

  • 1
    You ask "So my question is how can I convert this string to a list so that I can access and edit each letter of this word?" Did you happen to search "Python string to list" in Google yet? – dfundako Jul 24 '19 at 14:54
  • python has a `list` built-in to convert many things into lists. read the doc: https://docs.python.org/3/library/functions.html#func-list – njzk2 Jul 24 '19 at 14:56
  • 1
    @dfundako: That Google search is insufficient. It needs to be "Python string to list of characters, which yields [this](https://stackoverflow.com/questions/9833392/break-string-into-list-of-characters-in-python). – Robert Harvey Jul 24 '19 at 14:56
  • One thing you can do is convert the string to a `bytearray`. This will allow you to access and modify the string. For instance, `b = 'banana'`. If you do `b = bytearray(b)`, then you have access to converting individual characters with `ord` like so: `b[0] = ord('B')`. This will produce `Banana`. – Chrispresso Jul 24 '19 at 15:02

1 Answers1

1
stringInput="Banana"
listString=list(stringInput)

That's it. Easy peasy!

Pixel
  • 101
  • 7