AttributeError: 'function' object has no attribute 'replace' - python

I'm using this code to try to replace a character:
from another_test import test_once_more
test_once_more()
question = input("1 letter ")
for letter in question:
if letter == "a":
test_once_more.replace("1","a")
print (test_once_more)
This is the code I am using. All I want it to do is replace the 1 in this code.
def test_once_more():
print ("123456789")
and replace it with an "A"

You can't.
The function is printing something and returns None. There's no way to change that after the fact.
What you should do is have the function return a value and work on that:
def test_once_more():
return "123456789"
and then
from another_test import test_once_more
result = test_once_more()
question = input("1 letter ")
for letter in question:
if letter == "a":
result = result.replace("1","a")
print (result)
although I'm puzzled why you're using a for loop to iterate over a string that will be a single character (at least if your user follows your request)...

You have a very simple error here; test_once_more is the name of your function, while question is the name of your string. Try question.replace (and fix the other similar mistake).
P.S. strings cannot be mutated in Python, so you need to assign the result of calling replace to another variable in order to see the effect of calling replace().

Related

iterate through a tuple to form a string

I am trying to create a function named make_string, that uses * correctly with a parameter: strings
The function should return a string of all the values supplied joined, and separated by a space.
Outside the make_string function, I declare a variable named my_string, and assign the value returned from the make_string function.
Then I call the make_string function with the following values: "Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth". Finally I print the value of my_string to the terminal...and it returns None, when it should return Alderaan Coruscant Dagobah Endor Hoth
Can anybody tell me where I am going wrong please?
def make_string(*strings):
my_string = ""
for x in strings:
my_string = x.join(strings)
return my_string
my_string = make_string()
make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")
print(my_string)
There are a few things going on in your code that are a little wonky.
You're constantly re-assigning the value of my_string every time you loop through for x in strings
There's no reason to start with a blank string here since you're already using join
Your function call isn't setting to my_string -- it isn't set to anything. What you want is like my_string = make_string("Bob", "Mary") etc.
This should do the trick:
def make_string(*strings):
return " ".join(strings)
my_string = make_string("Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth")
print(my_string)
Personally, I would say you don't even need a function here, especially if you can easily set what you're using for *strings to a variable. For example:
planets = ["Alderaan", "Coruscant", "Dagobah", "Endor", "Hoth"]
print(" ".join(planets))

Checking input for the whole exact string in a list

So I'm creating a simple program to check the input for words contained in the list. I have something like this...
def function():
list = ["hell", "yeah"]
check_input = input("Sentence to check: ")
check_input.split()
check = any(item in check_input for item in list)
if check is True:
print("List word found!")
else:
print("Clean!")
The problem is I want it to check the input for the exact same string from the list. Not if the input contains just a part of it.
Basically: I want it so if the user types "hello world" into the input, check would return as false and print clean because "hello" isn't "hell".
I guess I need to use something different than any() function, but I can't come up with anything that would solve this.
Any ideas?
Your code is slightly wrong due to which it is not working correctly.
Replace check_input.split() with check_input=check_input.split()
Or use check_input = input("Sentence to check: ").split()

How can I delete an empty value created in a Python list?

I want to delete the empty values which are being created in Python list.
My code here - https://pastebin.com/whz7t4yR
I tried to solve 'String Task' problem from Codeforces
Every time a letter is found, I'm inserting a dot after that letter in the list. But an empty value is being created after that dot insertion.
I've tried to delete the empty values. But apparently, it only works for a particular test case("Codeforces"). For other two test cases, it shows
"IndexError: list index out of range"
for l in range(0,len(s)):
if(s[l] in letter and s[l+1] in letter):
s.insert(l+1, '.')
print("inside IF, index[",l,"]=>", s[l])
elif(s[l] in letter):
s.insert(l+1,'.')
#del (s[l+2])
print("inside ELIF, index[",l,"]=>", s[l])
else:
print("inside ELSE, index[",l,"]=>", s[l])
continue
Expected result:
.c.d.f.r.c.s
Actual result:
.c.d.f.r.cs
for l in range(0,len(s)):
if(...s[l+1]...)
These are in your first two lines, l+1 is guaranteed to get out of range of your list s
If you need to access the next element like this, change the range to for l in range(0,len(s)-1): instead so you know you'll always have a s[l+1] element
Try this. The complete solution.
st = input()
vowels = ['a','e','i','o','u','y']
for i in st.lower():
if i not in vowels:
print(f'.{i}', end='')
You can also use this easier method for the question:
word = input("").lower()
no_Vowel = word.translate({ord(change): None for change in "aoyeui"})
no_VowelsPoint = f".{no_Vowel}"
points = ".".join(no_Vowels).replace("..", ".")
print(points.lower())

How do I call .lower on a class object?

I have a class I've called Earthquake, and it has a location as a string, and a few other parts that aren't important to this question (I don't think).
I've written a function (filter_by_place) that iterates through a list of Earthquakes that I've passed it, and looks for a given word in each Earthquake location string. If the word is found in the Earthquake's location, then it adds that Earthquake to a list. My problem is that it cannot be case sensitive, and I'm trying to make it that way by looking for an all lowercase word in an all lowercase version of the location string.
def filter_by_place(quakes, word):
lst = []
for quake in quakes:
if word.lower in (quake.place).lower:
lst.append(quake)
return lst
I get an error saying "TypeError: argument of type 'builtin_function_or_method' is not itterable"
So, my question is: How do I get that string within the class to become lowercase just for this function so I can search for the word without worrying about case sensitivity?
I've already tried adding
if word.lower or word.upper in quake.place:
inside the for loop, but that didn't work, and I can understand why. Help?
You're getting the error because you're not actually calling the lower string function. I am guessing you're coming from ruby where this wouldn't be required.
Try:
def filter_by_place(quakes, word):
lst = []
for quake in quakes:
if word.lower() in quake.place.lower():
lst.append(quake)
return lst
You need to do word.lower(). You're missing the brackets. Happens all the time :)
Try this
def filter_by_place(quakes, word):
lst = []
for quake in quakes:
if word.lower() in quake.place.lower():
lst.append(quake)
return lst
Because you're using python, you might want to take a look at list comprehensions. You're code would then look something like this
def filter_by_place(quakes, place):
return [quake for quake in quakes if quakes.place.lower() is place]

If one or more letters equals the same as a variable; Python

I have some code:
multi = "testtest"
if(type[0] == multi[0]):
print("test")
But then if I run it, it works, but if I type t, the 1st letter, and then some other letters:
tfdsajfdsaf, it won't print test. Is there any other way I could make this work if the other letters are different?
Sounds like you might want to use startswith(), which is a part of the string class.
if string_name.startswith(multi[0]):
print 'test'
You can also use slices:
if string_name.startswith(multi[:3]):
print 'test'

Categories