Python fixed string size

Suppose I need n elements long with each element separated by a space. In addition, I need the i-th element to be 1, and the rest - 0. What is the easiest pythonic way to do this?

So, if n = 10and i = 2, I would like 0 1 0 0 0 0 0 0 0 0

I need something like new string[]that you can get in C ++, but the Python version eludes me.

Thank!

+3
source share
5 answers

Use a list.

n = 10
i = 2

mylist = ["0"] * n
mylist[i-1] = "1"
print " ".join(mylist)
+6
source

The following Python generator expression should produce what you are looking for:

" ".join("1" if i == (x+1) else "0" for x in range(n))
+2
source

Python REPL . Python " ".join(bin((1<<n)+(1<<n>>i))[3:]) .

>>> n=10
>>> i=2
>>> " ".join(bin((1<<n)+(1<<n>>i))[3:])
'0 1 0 0 0 0 0 0 0 0'
+1

, Python.

, n, '1' ( i) '0' ( ). .

. , , , , False, - True. '0' '1' (, integer, ).

new string[] - ++.

Edit

Python:

' '.join([('0', '1')[x == i - 1] for x in range(n)])

' '.join([str(int(x == i - 1)) for x in range(n)])

- , , - . i - 1 i, i x . . , , . , , , .

, . .

0

"+" :

("0 "*i + "1 " + "0 "*(n-i-1))[:-1]

or you can also use bytearray:

a = bytearray(("0 "*n)[:-1])
a[i*2] = "1"
print str(a)
0
source

All Articles