Is it possible to split a string in python and assign each piece split off to a variable to be used later? I would like to be able to split by length if possible, but im not sure how it would work using len().
i tried this but its not getting me what i needed:
x = 'this is a string'
x.split(' ', 1)
print x
result:
[‘this’]
i want to result to something like this:
a = 'this'
b = 'is'
c = 'a'
d = 'string'
If you’d like to access a string 3 characters at a time, you’re going to need to use slicing.
You can get a list of the 3-character long pieces of the string using a list comprehension like this:
The important bit is:
range(0, len(x), step)gets us the indices of the start of eachstep-character slice.for i inwill iterate over these indices.x[i:i+step]gets the slice ofxthat starts at the indexiand isstepcharacters long.If you know that you will get exactly four pieces every time, then you can do:
This will happen if
3 * step < len(x) <= 4 * step.If you don’t have exactly four pieces, then Python will give you a
ValueErrortrying to unpack this list. Because of this, I would consider this technique very brittle, and would not use it.You can simply do
Now, where you used to access
a, you can accessx_pieces[0]. Forb, you can usex_pieces[1]and so on. This allows you much more flexibility.