简体   繁体   中英

How to Iterate Over String using next?

There's a string:

x = '012846871'

how would I loop so it would give me how many 1's are in the string:

010000001

as in like x[0] has no 1's, x[1] has one 1 and so on.

You can use generator expression, for example something like this should work:

x = '012846871'
mask = ''.join('1' if digit == '1' else '0' for digit in x)
print(mask)

>>> 010000001

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM