porting the piece of code
I have following pieces of code:
code1:
lis = ["a", "s", "d"]
string.join(lis)
code2:
lis = ["a", "s", "d"]
' '.join(lis)
Results:
For both the cases the result is 'a s d'
Now, there should be certain cases (if I'm correct) when the value of 'sep' which is the default separation value differ from ' '. I would really like to know when does such cases occur ?
I have following doubts:
Is there any difference between the above two codes, more specifically in the 'join' statement in case of python2.x.
If 'yes', then how do I perform the task of 'code1' in python3.x because in python3.x string does not have the module 'join'
than开发者_Go百科ks in advance..
I had to look it up - large parts of the string
are obsolete (replaced by real methods on real str
objects); because of this, you should propably use ' '.join
even in Python 2. But no, there is no different - string.join
defaults to joining by single spaces (i.e. ' '.join
is equivalent).
There is no significant difference. In all cases where you could use the first form the second will work, and the second will continue to work on Python 3.
However, some people find that writing a method call on a literal string looks jarring, if you are one of these then there are a few other options to consider:
' '.join(iterable) # Maybe looks a bit odd or unfamiliar?
You can use a name instead of a literal string:
SPACE = ' '
...
SPACE.join(iterable) # Perhaps a bit more legible?
Or you can write it in a similar style to string.join()
, but be aware the arguments are the other way round:
str.join(' ', iterable)
Finally, the advanced option is to use an unbound method. e.g.
concatenate_lines = '\n'.join
...
print(concatenate_lines(iterable))
Any of these will work, just choose whichever you think reads best.
The two statements are equivalent.
string.join(words[, sep])
Concatenate a list or tuple of words with intervening occurrences of sep. The default value for sep is a single space character.
While for the second case:
str.join(iterable)
Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.
Since the second version still exists in Python 3, you can use that one without any problems.
Sources:
- Python 2.7.1 documentation of
string.join()
(static method) - Python 2.7.1 documentation of
join()
(string method)
string.join accepts a list or a tuple as parameter, wheras " ".join accepts any iterable.
if you want to pass a list or a tuple the two variants are equal. In python3 only the second variant exists afaik
精彩评论