manipulate string
Skip Montanaro
skip at pobox.com
Tue Oct 28 14:39:15 EST 2003
>>> s = "0123456789"
>>> " - ".join([s[i] for i in range(0, 10, 2)])
'0 - 2 - 4 - 6 - 8'
I thought the original poster wanted the odd numbers replaced by '-' and then
all elements separated by spaces. None of the ' - '.join(...) examples
achieve that, as they fail to replace '9' with '-'. Here's an alternative
which does:
>>> s = "0123456789"
>>> [int(c)%2 and '-' or c for c in s]
['0', '-', '2', '-', '4', '-', '6', '-', '8', '-']
>>> ' '.join([int(c)%2 and '-' or c for c in s])
'0 - 2 - 4 - 6 - 8 -'
Skip
More information about the Python-list
mailing list