Does anyone know the justification for this confusing set construction syntax? I spent a day unable to find this bug because I missed a comma in constructing a set.
> {1 2}
SyntaxError: invalid syntax # This makes sense.
> {'a' 'b'} = set(['ab']) # This does not.
That's not a set construction syntax thing. You're running into implicit string literal concatenation, a confusing and surprising corner of the language:
>>> 'a' 'b'
'ab'
If you write two string literals next to each other, they're implicitly combined into one string. (This only works with literals; str(3) str([])
is a syntax error, not '3[]'
.)
This has nothing to do with sets.
Two string literals separated by whitespace are considered one string literal.
rationale = ('This is quite useful when you need to construct '
'a long literal without useless "+" and without '
'the indentation and newlines which triple-quotes bring.')
Do you mean
>>> {'a' 'b'} == set(['ab'])
True
?
That's just because 2 strings are concatenated to 1 string:
>>> type('a' 'b')
<class 'str'>
>>> len('a' 'b')
2
>>> print('a' 'b')
ab
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.