Reputation:
My mini program takes a string from user input and adds dots between each letter and then removes these dots.
The function add_dots
takes the string and adds dots. I have a separate function called remove_dots
that then removes them.
Here is the code below:
def add_dots(str):
str = ".".join(str)
print(str)
def remove_dots(str):
str.replace(".", "")
print(str)
word = input("Enter a word: ")
When I call the two functions individually with
add_dots(word)
remove_dots(word)
I get the expected console output of
Enter a word: hello
h.e.l.l.o
hello
However, when I try to call
remove_dots(add_dots(word))
I get an error AttributeError: 'NoneType' object has no attribute 'replace'
I understand that this means the str
variable has the value of None
but I'm not sure why? Can anyone advise. Thanks
Upvotes: 0
Views: 5174
Reputation: 1
When you return in something in function, You have to convert return in other datatype such as list , string. In this case, Your first function it should be
def add_dots(string):
string = ".".join(string)
print(string)
return str(string)
And second function should be
def remove_dots(string):
string = string.replace(".", "")
print(string)
return str(string)
Because anything that return from function, It return "Nonetype" as default. And Nonetype no method __getitem__
ref:https://www.pythonpool.com/typeerror-nonetype-object-is-not-subscriptable/
Upvotes: 0
Reputation: 94
def add_dots(str):
str = ".".join(str)
print(str)
return str
def remove_dots(str):
str = str.replace(".", "")
print(str)
return str
this should fix your code.
See @Chris and @Michael Butscher comments on your post
Upvotes: 0
Reputation: 1817
Your functions don't return anything. Also, the output of str.replace(".", "")
is not stored. This should work.
def add_dots(str):
return ".".join(str)
def remove_dots(str):
return str.replace(".", "")
Upvotes: 0
Reputation: 3782
This is caused because your add_dots
and remove_dots
functions aren't actually returning anything, they're just printing values. Thus, passing the output of add_dots
to remove_dots
results in the value None
being passed.
Also note that using str
as a variable name is generally a bad idea; using string
or a more descriptive name is better practice.
Change your code to return the modified strings, like so:
def add_dots(string):
string = ".".join(string)
return string
def remove_dots(string):
string = string.replace(".", "")
return string
word = input("Enter a word: ")
And print the outputs like so:
print(add_dots(word))
print(remove_dots(word))
print(remove_dots(add_dots(word)))
Upvotes: 2