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()

3
  • 2
    Removing the spaces is simple enough with s = s.replace(" ", ""). As for the second question, does this address your issue? Commented Jul 7, 2014 at 3:45
  • You want it in 3-character chunks, excluding whitespace? Commented Jul 7, 2014 at 3:45
  • yes just 3 characters with no spaces Commented Jul 7, 2014 at 3:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
Yes, it'll give you all the items from 0 inclusive to 3 exclusive, ie the 0th 1st and 2nd items.
oooh thanks man. Yes I remember in slicing the last number basically means," up to but not including"
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)]
true but that is a little too advanced for me at the momment
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.