0

If I have a string 'banana peel' and I want to break it down to a width of 3 characters as in:

'ban'
'ana'
'pee'
'l'

How would I go about that? How would I remove the space/whitespace between 'banana' and 'peel' that is in the middle of the string and create the results above?

Only things that come to mind are things like list() and strip()

Robert Rocha
  • 9,510
  • 18
  • 69
  • 121

1 Answers1

1

Just like this:

string = "banana peel"
string = string.replace(" ", "")
results = []
for i in range(0, len(string), 3):
    results.append(string[i:i + 3])
print(results)

replace(" ", "") replaces all the spaces with nothing, giving bananapeel. range(0, len(string), 3) will give a list of numbers from 0 to the length of the string with an interval of 3. Each set gets added to the array for you to print in the end.

Will Richardson
  • 7,372
  • 6
  • 42
  • 54