11

I am currently writing a Python script to handle some logs and reformat certain parts. Part of the script makes use of the following code (as an example):

var1,var2,var3=foo.split("|")

Which works fine. However this perhaps doesn't look so nice (taking away Python's readability factor) if there are 39 values, for example:

var1,var2,var3,...,var39=foo.split("|")

Is there are a better way to format this structure?

codeforester
  • 39,467
  • 16
  • 112
  • 140
MHibbin
  • 1,135
  • 5
  • 19
  • 31

5 Answers5

31

You can assign to different variables. Like in Perl, you just need to define them in an array, so assignation is done by matching position of variable and result.

Here is something I tried in interactive python:

>>> # this is a grep result, btw
... foo = 'config/some.conf:12:   title = "Super Me"'
>>> [ filename, line, text ] = foo.split(':')
>>> print text
   title = "Super Me"

I do like this rather than a dictionary or an array, especially when working in a for loop. It makes variable names more meaningful, even if local to the loop, or temporary.

Edit
second edit to integrate codeforester's notes (Thanks).

To avoid searching for variables usage, unwanted values can be dummied to clearly state it will not be used. Dummy variables are expected as _ by python linter

>>> [ _, line, text ] = foo.split(':')

If you don't need the List properties with your variables, you can just remove the square brackets (variables are then managed as a tuple):

>>> filename, line, text  = foo.split(':')

If you are not sure about the tokens quantity, use the extended iterable, which requires a List:

>>> [ filename, line, text, *_ ] = foo.split(':')

End of edit

Readability for the win !

Mat M
  • 1,786
  • 24
  • 30
  • 2
    Python's way for dummy variables is to use `_`. – codeforester Nov 22 '20 at 03:42
  • 1
    Also, it may not be a good practice to assume that `split` would result in a certain number of fields. A safer approach would be to write `[filename, line, text, *_] = foo.split(':')` or simply `filename, line, text, *_ = foo.split(':')` – codeforester Nov 22 '20 at 03:55
  • This is great! What if I need to typecast first token into an int (say age) and leave second token as string (say first name)? Is there an easy way to do this type conversion in same line? – Amol Jan 26 '23 at 22:45
  • @Amol : AFAIK, you can't. Typecasting happens on the RVALUE, which is generated by the `split`. So, all your vars will be string by default. – Mat M Jan 27 '23 at 17:55
8
lst = foo.split("|")
lst[0]
lst[1]
...
applicative_functor
  • 4,926
  • 2
  • 23
  • 34
3

you can use a dictionary:

In [29]: strs="foo|bar|spam|eggs"

In [31]: d=dict(("var{0}".format(i),x) for i,x in enumerate(strs.split("|")))

In [32]: d
Out[32]: {'var0': 'foo', 'var1': 'bar', 'var2': 'spam', 'var3': 'eggs'}

In [33]: d['var1']
Out[33]: 'bar'

In [34]: d['var2']
Out[34]: 'spam'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

Use a list to store the tokens obtained: -

>>> my_str = "Python|Splitting|the|string"
>>> my_tokens = my_str.split("|")
>>>
>>> my_tokens
['Python', 'Splitting', 'the', 'string']
>>> my_token[0]
'Python'
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

This might be helpful for you:

strings = "python,splitting,the,string"

var1,var2,var3,var4 = [str(i) for i in strings.split(",")]
kmt
  • 773
  • 12
  • 30
Naret_17
  • 21
  • 1