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'
Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.
Unpack the values to split a string into multiple variables, e.g. a, b = my_str. split(' ') . The str. split() method will split the string into a list of strings, which can be assigned to variables in a single declaration.
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
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:
>>> x = 'this is a string'
>>> step = 3
>>> [x[i:i+step] for i in range(0, len(x), step)]
['thi', 's i', 's a', ' st', 'rin', 'g']
>>> step = 5
>>> [x[i:i+step] for i in range(0, len(x), step)]
['this ', 'is a ', 'strin', 'g']
The important bit is:
[x[i:i+step] for i in range(0, len(x), step)]
range(0, len(x), step)
gets us the indices of the start of each step
-character slice. for i in
will iterate over these indices. x[i:i+step]
gets the slice of x
that starts at the index i
and is step
characters long.
If you know that you will get exactly four pieces every time, then you can do:
a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)]
This will happen if 3 * step < len(x) <= 4 * step
.
If you don't have exactly four pieces, then Python will give you a ValueError
trying to unpack this list. Because of this, I would consider this technique very brittle, and would not use it.
You can simply do
x_pieces = [x[i:i+step] for i in range(0, len(x), step)]
Now, where you used to access a
, you can access x_pieces[0]
. For b
, you can use x_pieces[1]
and so on. This allows you much more flexibility.
You can use unpacking
a,b,c,d=x.split(' ');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With