-2

I am trying to split a string into several variables to eventually send each one as an instruction for one of six stepper motors. A string will be in a format like so:

D2 R' D' F2 B D R2 D2 R' F2 D' F2 U' B2 L2 U2 D R2 U

The issue is the steps within the string (e.g. D2 or R' or B) are all varying in length, so using step as a fixed length provides issues when recalling the individual sections (the varying lengths means that sometimes I will get part of one solution or a blank space then a letter). Also using something like unpacking doesn't work as the amount of steps in the string varies. So, how can I cut up a string like the one shown below, so I can assign each step to a individual variable?

From looking at a previous question (Python - split string into smaller chunks and assign a variable) I have realised I can do something along these lines:

finalstate = input("enter solution: ")
finalstate.split
step = 2
solution_steps = [finalstate[i:i+step] for i in range(0, len(finalstate),step)]

And then call upon the different chunks of the solution like so:

print(Solution_steps[0])

However, in that solution they wanted the string to be separated by a determined length and mine will vary.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Josh
  • 3
  • 1
  • 3
    `split` is a function, you have to call it with `()`. And you need to assign the result to another variable. – Barmar Feb 08 '21 at 19:29
  • You havent said where the splits are supposed to occur or what you'd expect as a final output. – Sayse Feb 08 '21 at 19:30
  • @sayse My apologies, i am new to this community and still learning the correct way to ask meaningful questions. I now realize my question had been answered previously, however, being newer to coding i am struggling to search for answers to my questions as i am unsure how to word them. Barmar has now solved my issue. – Josh Feb 08 '21 at 19:52

1 Answers1

1

You need to call the split method by putting () after it. And it returns a list, you need to assign that somewhere.

finalstate = input("enter solution: ")
words = finalstate.split()
step = 2
solution_steps = [words[i:i+step] for i in range(0, len(words),step)]

Value of solution_steps:

[['D2', "R'"], ["D'", 'F2'], ['B', 'D'], ['R2', 'D2'], ["R'", 'F2'], ["D'", 'F2'], ["U'", 'B2'], ['L2', 'U2'], ['D', 'R2'], ['U']]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Ahhhh i can't believe it was that silly, thank you so much for the prompt solution! Hope you're having a good day sir. – Josh Feb 08 '21 at 19:42