I’m pretty new to Python and am completely confused by
.join() which I have read is the preferred method for concatenating strings.
strid = repr(595) print array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring().join(strid)
and got something like:
Why does it work like this? Shouldn’t the
595 just be automatically appended?
Look carefully at your output:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5 ^ ^ ^
I’ve highlighted the “5”, “9”, “5” of your original string. The Python
join() method is a string method, and takes a list of things to join with the string. A simpler example might help explain:
>>> ",".join(["a", "b", "c"]) 'a,b,c'
The “,” is inserted between each element of the given list. In your case, your “list” is the string representation “595”, which is treated as the list [“5”, “9”, “5”].
It appears that you’re looking for
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring() + strid
join takes an iterable thing as an argument. Usually it’s a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:
which acts the same as this:
"wlfgALGbXOahekxSs".join(["5", "9", "5"])
and so produces your string:
Strings as iterables is one of the most confusing beginning issues with Python.
To append a string, just concatenate it with the
>>> a = "Hello, " >>> b = "world" >>> str = a + b >>> print str Hello, world
join connects strings together with a separator. The separator is what you
place right before the
>>> "-".join([a,b]) 'Hello, -world'
Join takes a list of strings as a parameter.
join() is for concatenating all list elements. For concatenating just two strings “+” would make more sense:
strid = repr(595) print array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring() + strid
To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:
strid = repr(595) print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring(), strid])
On providing this as input ,
li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret'] s = ";".join(li) print(s)
Python returns this as output :