clan
clan

Reputation: 353

Converting a string-like object into a string in python

I am using python and XMLBuilder, a module I downloaded off the internet (pypi). It returns an object, that works like a string (I can do print(x)) but when I use file.write(x) it crashes and throws an error in the XMLBuilder module.

I am just wondering how I can convert the object it returns into a string?

I have confirmed that I am writing to the file correctly.

I have already tried for example x = y although, as I thought, it just creates a pointer, and also x=x+" " put I still get an error. It also returns an string like object with "\n".

Any help on the matter would be greatly appreciated.

Upvotes: 1

Views: 198

Answers (4)

file.write(str(x))

will likely work for you.

Background information: Most types have a function __str__ or __repr__ (or both) defined. If you pass an object of such a type to print, it'll recognize that you did not pass a str and try to call one of these functions in order to convert the object to a string.

However, not all functions are as smart as print and will fail if you pass them something that is not a string. Also string concatenation does not work with mixed types. To work with these functions you'll have to convert the non-string-type objects manually, by wrapping them with str(). So for example:

x = str(x)+" "

This will create a new string and assign it to the variable x, which held the object before (you lose that object now!).

Upvotes: 1

Aamir Rind
Aamir Rind

Reputation: 39659

The Library has __str__ defined:

def __str__(self):
    return tostring(~self, self.__document()['encoding'])

So you just need to use str(x):

file.write(str(x))

Upvotes: 1

halflings
halflings

Reputation: 1538

When you write:

print myObject

The __repr__ method is actually called.

So for example you could do: x += myXMLObject.__repr__() if you want to append the string representation of that object to your x variable.

Upvotes: 0

mgilson
mgilson

Reputation: 309891

I'm not quite sure what your question is, but print automatically calls str on all of it's arguments ... So if you want the same output as print to be put into your file, then myfile.write(str(whatever)) will put the same text in myfile that print (x) would have put into the file (minus a trailing newline that print puts in there).

Upvotes: 0

Related Questions