Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ryan Ruscett
23,309 PointsPython replace baffling me.
Ok so here it goes.
def __init__(self, ids, usr, pwd, dsc) :
self.id = ids
print self.id + "hello"
if " " in self.id :
print "Ok has spaces"
print type(self.id)
self.id.replace(" ", "_")
print self.id
Ok So I get 4 variables I create self.id. I print the id with the word hello next to it. Then I do an if statement. If the variable has white spaces, cool print ok it has spaces. Then I find out what type it is. Just to make double sure its a string. I then do a replace on the white spaces with _ and print the variable again.
OUTPUT
wer eeq hello
Ok has spaces
<type 'str'>
wer eeq <<< -------WTF?
I print it, you can see yes it has a white space. The if method sees that and prints Ok has spaces. I double check it's a string which it is Then I do the replace print again but no _??? I have been staring at this and can't figure it out. It works in the interpreter, I tried re.sub nothing will change this string. Which makes me wonder if it's actually a string even though it says it is. There are no errors or anything.
So I am hoping you guys can help me out!
1 Answer
Ryan Ruscett
23,309 PointsOHHHH BOOYYY!!! Sitting at the computer to long, went and got a beer and then DUH! lol
So if I do this
name = "John Doe"
name.replace(" ", "_")
In the interpreter the immediate response back is John_Doe. BUT, after lookin at the code for replace. It returns a variable. BUT I am not storing the variable that it's returning in anything. So I did this instead and it worked like a charm.
def __init__(self, ids, usr, pwd, dsc) :
self.id = ids
if " " in self.id :
self.id = self.id.replace(" ", "_")
print self.id
Now when I pickle my stuff to a file, I can read it back from the file a lot lot better, considering I don't need to watch for spaces. And since the passwords and all the data is encrypted. It's not like you can read the file anyway. Ahhh dang. Finally past this this.
Later