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
  • 10,126
  • 19
  • 78
  • 130

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,780
  • 7
  • 42
  • 56
  • all righty then. the `results.append(string[i:i + 3])` is basically the same as: `results.append(string[0:0 + 3])` in the first run? I am fairly new to slicing. – Robert Jul 07 '14 at 03:52
  • Yes, it'll give you all the items from 0 inclusive to 3 exclusive, ie the 0th 1st and 2nd items. – Will Richardson Jul 07 '14 at 03:54
  • oooh thanks man. Yes I remember in slicing the last number basically means," up to but not including" – Robert Jul 07 '14 at 03:55
  • You could also use a list comprehension instead of the for loop+append: `[string[i:i+3] for i in range(0, len(string), 3)]` – Peter Gibson Jul 07 '14 at 03:56
  • true but that is a little too advanced for me at the momment – Robert Jul 07 '14 at 03:57
  • i am coming from a PHP background where there is no such thing as list comprehension – Robert Jul 07 '14 at 03:57