Reputation: 25
I need some help with creating a python class and method. I don't really know what I am doing wrong but I keep getting the correct answer and then this error:
<__main__.stringToMerge object at 0x7f9161925fd0>
I want to create an object with two string that merges them alternatively. For example the object would be obj.s1="aaaaa"
, obj.s2="bb"
and the correct output would be: "ababaaa"
.
Ty in advance for any help provided :D
class stringToMerge:
def __init__(self, string1, string2):
self.string1 = string1
self.string2 = string2
def SM(self, string1, string2):
self.string1 = string1
self.string2 = string2
string3 = ""
i = 0
while i<len(string1) and i<len(string2):
string3 = string3+string1[i]
string3 = string3+string2[i]
i = i+1
while i<len(string1):
string3 = string3+string1[i]
i = i+1
while i<len(string2):
string3 = string3+string1[i]
i = i+1
print(string3)
obj = stringToMerge('aaaaa', 'bb')
obj.SM(obj.string1, obj.string2)
print(obj)
Upvotes: 0
Views: 113
Reputation: 21
Your main Issue was that you were not returning anything and you were trying to print the object. Hence the reason it printed out <main.stringToMerge object at 0x7f9161925fd0>. In the snippet below I edited the code to be more concise, and I added a return statement to the function. Once this was done, I assigned a variable to the return value of the SM() method and printed said variable
class stringToMerge:
def __init__(self, string1, string2):
self.string1 = string1
self.string2 = string2
def longestString(string1,string2):
if len(string1) < len(string2):
return string2
else:
return string1
def SM(self, string1, string2):
string3 = ""
i = 0
for char1,char2 in zip(string1, string2):
string3 += char1+char2
i+= 1
longestString = stringToMerge.longestString(string1,string2)
return string3+longestString[i:]
obj = stringToMerge('aaaaa', 'bb')
final = obj.SM(obj.string1, obj.string2)
print(final)
Upvotes: 0
Reputation: 91
Already your code is printing the expected output. But additionally you are getting this message <__main__.stringToMerge object at 0x7f9161925fd0>
because you are printing the instance of the class print(obj)
. Comment or remove this line you won't find this again.
Upvotes: 1