1

I created a graph in Networkx by importing edge information in through nx.read_edgelist(). This all works fine and the graph loads.

The problem is when I print the neighbors of a node, I get the following for example...

[u'own', u'record', u'spending', u'companies', u'back', u'shares', u'their', u'amounts', u'are', u'buying']

This happens for all calls to the nodes and edges of the graph. It is obviously not changing the names of the nodes seeing as it is outside of the quotations.

Can someone advise me how to get rid of these 'u's when printing out the graph nodes.

I am a Python novice and I'm sure it is something very obvious and easy.

billett
  • 432
  • 1
  • 5
  • 13
  • 4
    That is not a problem, those are simply unicode strings. – Cory Kramer Sep 16 '14 at 14:54
  • also, if you absolutely need it: `str(u'a unicode string') == 'a regular string'`... – Corley Brigman Sep 16 '14 at 15:03
  • If you move to Python 3, unicode strings are the default, and it's _bytestrings_ (non-unicode strings) that are printed differently. But if you're in Python 2, and not about to move yet? Learn to love it. Needlessly encoding your strings will bring pain and suffering. OTOH, if your goal is to use them with a JSON parser, use a JSON generator, don't blindly trust `repr()` to do the right thing. – Charles Duffy Sep 16 '14 at 15:09

3 Answers3

1

You don't need to get rid of them, they don't do anything other than specify the encoding type. This can be helpful sometimes, but I can't think of a time when it isn't helpful.

andrew
  • 448
  • 7
  • 13
  • Well, if these strings are to be printed to an end-user, they should not see the `u`. I agree they are not a 'bug', but there is still a good question here. – Aaron McDaid Sep 16 '14 at 15:09
  • @AaronMcDaid, why would you show `repr()` results to a nontechnical end user at al? That just seems like a bad idea in general. If that user expects, say, JSON, then the `json` module can generate that. – Charles Duffy Sep 16 '14 at 15:10
  • I understand now. It is still off rather putting to have it printed out every time. – billett Sep 16 '14 at 15:17
  • @user3687671 Don't dump raw data structures to the user; print them with formatted strings. – chepner Sep 16 '14 at 15:44
1

If you are looking for a way to print a list of unicode strings without all of the extra formatting such as the brackets, quotes and unicode designator, try this:

>>> mylist = [u'own', u'record', u'spending', u'companies', u'back', u'shares', u'their', u'amounts', u'are', u'buying']
>>> print ', '.join(mylist)
own, record, spending, companies, back, shares, their, amounts, are, buying
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

You could do something like:

print '[' + ', '.join(node.neighbors) + ']'

instead of:

print node.neighbors

which implicitly usesrepr()on the list and its members.

martineau
  • 119,623
  • 25
  • 170
  • 301