Giannis
Giannis

Reputation: 5526

Python RDF lib - String value for nodes

I am using RDF lib to retrieve values from an online triple store.

I was wondering whats the ideal way of turning URIRef and Literals to plain string objects?

For example :

value = g.value(s,FOAF.page)

Should I be using value.n3(), or value.__str__() ? Is there any difference ? On my tests, both return a sting that looks the same.

Initially I was just storing the value, but turns out it causes problems during String comparisons, so I would like to just store a string, as there is no rdf-related processing after the extraction.

Upvotes: 2

Views: 3383

Answers (1)

Joe
Joe

Reputation: 31057

If you want the string contents of a literal, use str(value). Note that this throws away some information -- the datatype and the language -- that are part of the RDF model.

For comparison:

lit = rdflib.term.Literal('Literal\nvalue', lang='en')

print(str(lit))
print('---')
print(lit.n3())

gives:

Literal
value
---
"""Literal
value"""@en

It sounds like you want the former.

See pydoc3 rdflib.term.Literal.n3 for more detail on what the n3() method returns.

Upvotes: 3

Related Questions