python len method not good - python

So I am trying to do the MacDonald challenge.Given a function with the parameter "name", return the MacDonald version of it, the 1st and 4th letter being capitalized.
If I try the code without any if else and I pass in just "mac" an error occurs.So I said that if the length of name is less than 5 letters, print out that name is too short.Otherwise, do the macdonald version.
However, for some reason len() gives out an error here.
def old_macdonald(name):
firstLetter = name[0].capitalize()
fourthLetter = name[3].capitalize()
inBetween = name[1:3]
last = name[4:]
newName = firstLetter + inBetween + fourthLetter + last
if len(newName) < 4:
print("name is too short.")
else:
print(newName)
old_macdonald("mac")

I don't think len is throwing the exception, but just as the version without if condition the string manipulation does.
Do the string manipulation in the else part of your code to avoid the exception.

Following Jens' advice, I included the if check above everything else (since you want to terminate the function if the name is too short) and returned in the if-check to break end the function.
def old_macdonald(name):
if len(name)< 4:
print("name is too short.")
return
firstLetter = name[0].capitalize()
fourthLetter = name[3].capitalize()
inBetween = name[1:3]
last = name[4:]
newName = firstLetter + inBetween + fourthLetter + last
print(newName)
old_macdonald("mac")
old_macdonald("macdonald")
Here is the result

You are still trying to perform the same operations anyway, len is not throwing you an error, the above part of the code is giving you error.
Simply move your code to the else part of function and you should be fine. The reason you need to do this is because you need to check first, and then perform, instead of performing and then checking.

Related

How to add input in the middle of a string?

I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to figure it out lol.
what I'm trying to do is:
Wow (PlayerName) that's cool
so far what I have is:
name = input("Name? ")
print("Wow") (print(name)) (print("that's cool"))
python came back with an error saying object 'NoneType' is not callable, so instead i tried to write it as a function and call that instead:
name = input("Name? ")
def name_call():
print(name)
print("Wow") (name_call()) (print("that's cool"))
same issue, I tried various similar things, but at this point I'm just throwing darts
I'm not 100% sure why neither of these worked, but I do know that it probably has something to do with me writing it incorrectly. I could just print the name on a new line, but I want to try and put them all on the same line if possible.
you can try this code:
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'Wow that\'s cool!'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = (input('Please input name = '))
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 3
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
The result will be like this:
The original string is : Wow that's cool!
Please input name = Alice
Formulated String : Wow Alice that's cool!
you can input any name to the program.
As others have said, I think you're looking for string interpolation. As of Python 3.6 we have f-strings.
name = input("Name? ")
print(f"Wow {name} that's cool")
https://www.programiz.com/python-programming/string-interpolation
Your print's need to be on new lines.
name = input("Name? ")
print("Wow")
print(name)
print("that's cool")
Python thinks you are trying to call the result of the print function (which returns None) as a function of its own.
|
V you are accidentally calling the return value here
print("Wow")(print(name))
val = 'name'
print(f"Wow {val} that's cool.")
Btw, if you want name_call() to play a role, the following code also works
def name_call():
return ('name')
print(f"Wow {name_call()} that's cool.")
You may use the format method to insert name into the string's placeholder {}:
print("Wow {} that's cool".format(str(name)))
x = str(input('Name: '))
print('user entered {} as their name'.format(x))

Weird error in loop not understanding why the range is out of index

I was asked to:-
Write a program to input a string and then using a function change(), create a new string
with all the consonants deleted from the string. The function should take in the string as
a parameter and return the converted string.
my code :-
str=input("enter a string: ")
def change(stri):
for i in range(0,len(stri)):
for e in ['a','e','i','o','u','A','E','I','O','U']:
if stri[i]==e:
if i==len(stri)-1:
stri = stri[0:i-1] + "" + stri[i: ]
else:
stri = stri[0:i] + "" + stri[i+1: ]
else:
continue
return stri
str=change(str)
print(str)
output :-
Traceback (most recent call last):
File "main.py", line 13, in <module> str=change(str)
File "main.py", line 5, in change if stri[i]==e:
IndexEnoi: string index out of range
^ for any string
Please someone help me out this is my imp project
As said by Johny Mopp: "Let's say len(stri) == 10. Your for loop then is for i in range(0, 10):. But then in the loop you modify stri so that it's new length is less than 10. You will now get an index out of range error at if stri[i]==e: because i is too large"
Use this instead:
text=input("enter a string: ")
vowels = ['a','e','i','o','u','A','E','I','O','U']
for x in vowels:
text = text.replace(x,"")
print(text)
Generally speaking, don't try to reinvent the wheel. Make use of all functions Python offers you.
The issue you are facing is common when deleting from the same object that you are iterating. Eventually you delete a part of the object that is already queued up as part of a future iteration in the for loop and you get an error.
The best way around this, in your case, is to write your vowel only string out to a new variable keeping your stri variable intact as it was passed into your function.
A quick rewrite of your code with the addition of the new variable to catch your output string would look like:
vowels=['a','e','i','o','u','A','E','I','O','U']
stri='This is a test string'
stro=''
for character in stri:
if character in vowels:
stro=stro+character
print(stro)
I believe the issue you have is that you change the string inside the for loop. You delete letters but still have the same range (len(stri) is not updated while changing the stri). Try with the word without vowels. You will not get any error.
But there is a much simpler way of doing this if I understand your task correctly.
def change2(str):
return ''.join([letter for letter in str if letter not in ['a','e','i','o','u','A','E','I','O','U']])
print(change2(input('enter a string: ')))
The join method creates the new string and returns it. The separator between the list elements is a string that calls join() method. In this example, it is an empty string.
You should use a new string variable for concatenation. You are changing the passed string to the function that's why it gives the error.
str=input("enter a string: ")
def change(stri):
nstr = ''
for i in range(0,len(stri)):
for e in ['a','e','i','o','u','A','E','I','O','U']:
print(stri[i])
if stri[i]==e:
if i==len(stri)-1:
nstr = stri[0:i-1] + "" + stri[i: ]
else:
nstr = stri[0:i] + "" + stri[i+1: ]
else:
continue
return nstr
str=change(str)
print(str)

Can two identical strings not be equal to each other in Python?

Below is the code in question:
def search():
name = enter.get()
print(name)
name = name.lower()
data = open("moredata.txt")
found = False
results = str()
for line in data:
record = line.split("|")
record[0] = str(record[0])
print("'" + name + "'" "---" + "'" + record[0] + "'")
if record[0] == name:
found = True
line = str(line)
results += line
results = str(results).lstrip(' ')
continue
else:
found = False
continue
if not found:
print("No results found")
else:
print("These items match your search query:\n")
print(results)
# print(results)
print('\n---------------------------------\n')
In the text file I am using, pieces of information are separated by '|' and the function splits each piece into an array (I think?) and compares just the first value to what I put in the search bar.
I have used other text files with the same exact function, it works just fine: it verifies that the two strings are equal and then displays the entire line of the text file corresponding to what I wanted. However, when I search "a" which should register as equal to "a" from the line a|a|a|a|a|a in my text file, it doesn't. I know this is going to bite me later if I don't figure it out and move on because it works in some cases.
The line
print("'" + name + "'" "---" + "'" + record[0] + "'")
results in
'a'---'a'
'a'---'a'
'a'---'b'
when compared to lines
a|a|a|a|a|a
a|a|a|a|a|a
b|b|b|b|b|b
There are no empty lines between results, and both variable types are str().
The continue in your if statement in the loop is what's causing the problem as it should be a break.
Your program is finding it, but it's then being overwritten by the last iteration. Once your program has found, you should either never set found back to false, or preferably just cease the iteration altogether.
I would wager the other files you've tested with all end with the name that you were looking for, and this one is causing a problem because the name you're looking for isn't at the end.
Additionally, though technically not a problem, the other continue under the else in the for loop isn't necessary.
Your found variable is being overwritten on each iteration of the loop.
Therefore it will only be True if the last result matches.
You don't actually need your found variable at all. If there are results, your results variable will have data in it and you can test for that.

How to add space before a particular string in python

I have the following output after removing all spaces from a string
テレビを付けて
テレビつけて
つけて
テレビをオンにして
However, I'm trying to add a space either after the を character, or before つけて after テレビ
The desired output is as follows
テレビを 付けて
テレビ つけて
つけて
テレビを オンにして
I've tried to use some def function but not sure how to finish it off, or even if it'll work.
def teform(txt):
if x = "オンにして":
return " して"
elif y = "つけて":
return " つけて"
elif z = "付けて":
return " 付けて"
else:
return # ...(not sure what goes here)
You cannot use = to compare items, you must use ==.
Apart from the wrong comparing syntax, it seems you don't really know how to approach this – you don't need a loop of any kind. Just use txt.replace to target and change those specific substrings:
def teform(txt):
# add a space after を
txt = txt.replace ('を','を ')
# add a space between テレビ and つけて
txt = txt.replace ('テレビつけて', 'テレビ つけて')
return txt

python -- for with an if statement

I dont understand why, when i run my code the for each loop under the if statement isn't run. Even when the number of found is greater than 0!
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.finditer(commit_msg)
found = getIterLength(group)
print found
if found > 0:
issues = 0
for match in group:
print " print matched issues:"
auth = soap.login(jirauser,passwd)
print match.group(0)
getIssue(auth,match.group(0))
issues = issues + 1
else:
sys.exit("No issue patterns found.")
print "Retrieved issues: " + str(issues)
Any help would be appreciated, I have been banging my head on this for an hour.
Your getIterLength() function is finding the length by exhausting the iterator returned by finditer(). You would then need a new iterator instance for the for loop. Instead, I would restructure your code like this:
def findpattern(commit_msg):
pattern = re.compile("\w\w*-\d\d*")
group = pattern.finditer(commit_msg)
found = 0
issues = 0
for match in group:
print " print matched issues:"
auth = soap.login(jirauser,passwd)
print match.group(0)
getIssue(auth,match.group(0))
issues = issues + 1
found += 1
if found == 0:
sys.exit("No issue patterns found.")
print "Retrieved issues: " + str(issues)
OR, you could use the findall() method instead of finditer() to give you a list (which is an iterable, not an iterator) on which you can run len(group) to get the size and then use it to iterate over in your for loop.
Check your code formatting it looks like under the for you have a double tab instead of a single tab, remember python is very picky about indentation

Categories

Resources