54

Given a string "VAR=value" I want to split it (only) at the first '=' sign (< value > may contain more '=' signs), something like this:

var, sep, value = "VAR=value".partition('=')

Is there a way to NOT declare a variable 'sep'? Like this (just made up the syntax):

var, -, value = "VAR=value".partition('=')

Just for completeness, I'm targetting Python v 2.6

3
  • Probably worth pointing out here in the comments that in this case, you would actually use split instead of partition. That is, var, value = 'VAR=value'.split('='). Good, succinct example though. Apr 7, 2014 at 16:14
  • @Cody split only works in this case with a maxsplit argument. partition seems to be preferred. See comments below stackoverflow.com/a/2745082/11545 for details from people more knowledgeable than me Apr 7, 2014 at 21:43
  • The maxsplit argument specifies how many splits are made, so maxsplit=1 would be used here, i.e., at most one split into at most two pieces. This can be confusing because some other scripting languages (Perl, PowerShell, etc) use a similar parameter to specify instead how many substrings are created, so the argument in those cases would then be 2 instead of 1. This must be a source of subtle bugs when porting scripts. May 3, 2016 at 1:25

9 Answers 9

61

_ is indeed a very popular choice for "a name which doesn't matter" -- it's a legal name, visually unobtrusive, etc. However sometimes these very qualities can hinder you. For example, the GNU gettext module for I18N and L10N, which is part of Python's standard library, idiomatically uses _ very differently, with idioms such as...:

_ = gettext.gettext
# ...
print _('This is a translatable string.')

to mark and translate all the literal-string messages in the code (also exploiting the relative visual unobtrusiveness of _('...'). Obviously any code using this module and idiom shouldn't also be using _ to mean something completely different ("a don't care name").

So a second useful alternative can be to devote the name unused to indicate such "don't care" situations in a visually more explicit way. Google's python style guide recommends using either _ or a prefix of unused_ -- the latter can be a bit verbose but tends to be very clear, e.g.:

name, unused_surname, salutation = person_data
print "Hello, %s %s!" % (salutation, name)

makes crystal-clear that person_data is a three-item sequence (probably a tuple) and the item you're skipping (and not using at all) is the surname (because you want to print a friendly message like "Hello, Mr Alex!" or "Hello, Miss Piggy!" ;-). (pylint and similar tools can warn you if you have unused variables named otherwise than _ or unused_..., and of course also warn you if you ever do use a variable named unused_something!-).

1
  • Nice point on gettext, I think I might done that sometime without realising. Oct 19, 2017 at 7:30
16

Almost there:

var, _, value = "VAR=value".partition('=')

_ is conventionally considered a don't-care variable.

3
  • 1
    Out of curiosity, what's the convention for multiple don't-cares? Just keep adding _ characters? Or reuse the same _ name?
    – Hank Gay
    Apr 30, 2010 at 14:20
  • 3
    @Hank: you can just re-use single underscore, also if those variables come in a sequence you could just pack them back into a tuple, like this: a, *_, e = range(5). In py2k *_ can only be last parameter Apr 30, 2010 at 14:23
  • 6
    I think you're mistaken: Python 2.x doesn't allow this assignment syntax at all. Apr 30, 2010 at 14:52
4

There isn't anything official in the language for that; you can just use any throw-away variable. As far as standards go, I've seen underscores used occasionally in Python and other languages. The only issue there is that underscore is used as an alias for gettext when localizing. But if you aren't doing localization, or aren't using the global-binding for it, then underscore should work fine.

3

Really strange question, because you can do just:

var, _, value = s.partition(sep)

and don't care about _ variable, but _ is just a name as sep, as var or value. By the way use str.split

>>> var, value = "VAR=value".split('=')
>>> var, value
('VAR', 'value')
>>> 
4
  • 2
    str.split is much slower and str.partition is designed for exactly this situation. Apr 30, 2010 at 14:21
  • 1
    @Silent Guys, str.partition splits only at the first occurence of 'sep', so if I have var,_,value = "AAA=bbb=ccc", value will be assigned 'bbb=ccc' which is what I want; str.split splits at each occurence of 'sep'; there are more differences, see the docs. docs.python.org/release/2.5.2/lib/string-methods.html Apr 30, 2010 at 14:31
  • 4
    @Cristi Diaconescu: split has a maxsplit parameter.
    – mg.
    Apr 30, 2010 at 15:05
  • 1
    One major issue with split() is the number of results varies while partition() always gives 3 results. So, (a,b) = "something".split(',') throws an error while (a, sep, b) = "something".partition(',') does not. Jul 22, 2015 at 12:56
2
  • Python doesn't have syntax to avoid assignment in unpacking and such.

  • As others have mentioned, there is a convention of using _ for variables you don't care about. This is fairly broadly used and understood, but personally I think it is underused. If you say var, _, value = "VAR=value".partition('='), you have to know what's going on to know what the _ was and why you didn't care about it when you read the code. If you say var, sep, value you document at the same time. This isn't very important for str.partition, but I've seen _, _, name, _, city, _ = some_weird_function() before and found it less useful than if everything was unpacked to useful names.

  • You could technically use str.split here if you wanted to. var, value = "foo=bar=baz".split("=", 1).

2

Why don't you use 'VAR=value'.split('=') instead? That disregards the delimiter.

EDIT (to accommodate Cristi's example in the comment):

From Diving into Python:

Tip: anystring.split(delimiter, 1) is a useful technique when you want to search a string for a substring and then work with everything before the substring (which ends up in the first element of the returned list) and everything after it (which ends up in the second element).

2
  • 4
    because <value> may contain more '=' characters, and I only want to split at the first one. Apr 30, 2010 at 14:33
  • 1
    Try 'VAR=value=full=of=equal=signs'.split('=',1).
    – PaulMcG
    Apr 30, 2010 at 18:10
1

The _ is commonly used as a name for you dont care * For example, in a tuple containing the name, surname and nickname in a moment in which we are interested only in name and surname, could use _ to indicate that the name is not important at this point:

data = ('John', 'Mate', 'Little John')
name, surname, _ = data
1

As others have said, underscore (_) is the standard. But if underscore is being used for translations, I think double underscore is the best alternative.

var, __, value = "VAR=value".partition('=')

Better than these:

var, unused, value = "VAR=value".partition('=')

var, unused_del, value = "VAR=value".partition('=')

var, _del, value = "VAR=value".partition('=')

-1

For numpy ndarrays, one can use indexing to choose particular elements:

arr_0, arr_2 = arr[[0, 2]]
1
  • This does not work if my_list is actually a list, only for Numpy arrays. Mar 18, 2023 at 5:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.