SmallChess
SmallChess

Reputation: 8116

How to iterate a Unicode string in Python?

I have a string, and I want to add unique non-ASCII characters to it. I need to do it in a loop because I may need to add more than one. The problem is that I don't know how to construct a proper Unicode string in the loop.

For example, I would like to add \u2713, \u2714, \u2715 etc to my string. I'm not sure how to do it.

s = 'ABCD'

for j in range(10):        
    s = s + u'\u2713'
    #s = s + (u'\u2713' + j) # This doesn't work

print s

Upvotes: 1

Views: 479

Answers (1)

falsetru
falsetru

Reputation: 369064

You can use unichr (chr in Python 3.x) to convert int to unicode string:

s = 'ABCD'

for i in range(10):
    s += unichr(0x2713 + i)

print s

prints ABCD✓✔✕✖✗✘✙✚✛✜


Instead of appending characters, you can use str.join (or unicode.join):

s = 'ABCD' + u''.join(unichr(0x2713 + i) for i in range(10))

OR

s = 'ABCD' + u''.join(unichr(ch) for ch in range(0x2713, 0x271d))

OR

s = 'ABCD' + u''.join(map(unichr, range(0x2713, 0x271d)))

Upvotes: 4

Related Questions