February 15th, 2013, 09:36 AM
Cut a string
I am begining with python and i have a problem.
I have the following string : "ABCAABBCC"
I want to cut this string afther or before the "B"
but this step is not yet importat so lets just assume before the "B".
i want to append the cutted parts to a list, which would look like this:
# It is very important that there are no charters lost.
I'm trying my best but i thnk there are more easy ways of doing this i just don't know them yet. I was hoping somone could help me with this dilema.
Help is very appriciated !
February 15th, 2013, 10:58 AM
a=s.split("B"); #now a =['A', 'CAA', '', 'CC']
b=["B"+i for i in a[1:]]; #now b=['BCAA', 'B', 'BCC']
b.insert(0,a);# add the first element back in
Comments on this post
February 15th, 2013, 11:53 AM
wow, this is exactly the kind of answer I don't like. The answer is correct and all, but I don't think it taught Richard anything, I'm struggling myself to read and decode that crypto answer(no offence)
Richard, the way I think about problems is that the best thing to do is often to split the problem into smaller and smaller parts until you know you can do all the small parts.
I usually make sections in my code with comments, and then just fill in the sections when i find the solutions. Like this.
#make an output list
#Make an empty temporary list
#add 0 to the start of the list
#Fill the List with the locations of all the B's
#Use a loop, that loops through every letter in the list, and adds the location if it is a B, to the temporary list
#add the length of the list to the end
#cut between the first item in the list to the second, second to third.... and append the cut into the outputlist. stop when done.
if this is too hard for you, divide it into smaller sections, or/and google on how to make loops, divide up strings and such.
ps. the first item in a list, is at index 0, not index 1. This might give you a headache at first. so "A" is at index 0, and B is at index 1, and "J" is at index 2 in this string: "ABJKSADB"
pps. slicing up string like this: "hello"[0:2] will return "he" and not "hel". (because the slice will slice TO the 2 index, but not actually include it)
February 15th, 2013, 12:20 PM
Since Richard did not post any code tries, he was more likely looking for someone to do the work for him. The reply posted was perfectly legitimate as it requires some effort on the part of the OP to use it, as opposed to simple code for someone using a forum as a personal, free programmer.
February 15th, 2013, 01:54 PM
I am a newbie so perhaps this is totally wrong.
a = "ABCAABBCC"
a = a.replace('B', ' B').split()