mardi 1 octobre 2019

Splitting a string at random position and adding resulting parts to a list

I just started with Python coding and ran into something I thought is very easy to solve (at least with the help of Google...):

I have a string which I want to split at a random position. The resulting parts of the string should be added to a list, e.g. str = "abcdefg" --> list = ["abc","defg"] In this example it was suggested to me to determine a random delimiter within the string (with randrange), split at this delimiter and put the parts together. That works fine, I understood the code and was able to modify it slightly. However, when the string contains a character more than once, this method cuts at every occurrence because of the fixed delimiter.

How would one achieve the following: str = "abcdabcd" --> list = ["abc","dabcd"]?

I was thinking about iterating over the characters of the string, but how would I implement the "split at a random position" requirement?

Thank you very much in advance




Aucun commentaire:

Enregistrer un commentaire