lily
lily

Reputation: 328

how to deal with numbers with `u''` in python?

I'm using NetworkX to read some data. The data format is like u1, u12. For example, in the library, there is a list:

networkx_lista = [u'1', u'3', u'12'].

Now I want to search for u3, but I only have an integer c=3.

Is there a function that can convert c into u'3'? Like:

networkx_lista.search(unicode(c))

I tried chr() and unichr(), it seems they produce only '\x03' or u'\x03', not u3.

Upvotes: 1

Views: 2814

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1124170

You don't have numbers; you have unicode strings. Convert your strings to numbers with int(), or your integer number to a unicode string.

unicode() will do fine for the latter approach, as does str() as Python will automatically encode / decode values to compare byte strings and Unicode values.

You can use any() or in membership testing here:

any(int(v) == c for v in networkx_lista)

or

unicode(c) in networkx_lista
str(c) in networkx_lista

If you don't need the list to be unicode strings, you can always convert the list to hold integers instead, once, and be done with it:

networkx_lista = [int(x) for x in networkx_lista]

and save yourself the trouble of having to convert either c or the contents each time you need to test membership.

Upvotes: 3

Pranav Raj
Pranav Raj

Reputation: 873

You can convert int to string and search it in list. For example, the follwing piece of code will print 'True'

num = 3
print str(num) in networkx_lista

Upvotes: 0

Óscar López
Óscar López

Reputation: 236124

The data is represented as strings, not numbers. The u simply means that it's an unicode string. Try this:

'3' in [u'1', u'3', u'12']
=> True

As you can see, I'm treating the number 3 as a string '3'. Alternatively, you can convert the input list of strings into a list of integers:

networkx_lista = [u'1', u'3', u'12']
networkx_lista = [int(x) for x in networkx_lista]

Now you can directly search for integer values in the list:

3 in networkx_lista
=> True

Upvotes: 6

Related Questions