Python printes unwanted letter after telling it not to - python

I wanted to create a translator, so I looked at some videos online and found one that showed how to substitute certain letters in a sentence and turn them into other letters/symbols. I tried doing it and it worked. But once I started adding new other letters for it to look for. It started printing the letter that was supposed to have been substituted.
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "ㅏ": #if ㅏ then A
translation = translation + "A"
if letter in "Б": #if Б then B
translation = translation + "B"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
I am planning on adding the whole alphabet, so I can't have it print the unwanted "supposed to have been substituted letter". I have tried all I can. But I simply can't get it to work. Any thoughts?

You need to combine the if statements like so:
if letter in "ㅏ": #if ㅏ then A
translation = translation + "A"
elif letter in "Б": #if Б then B
translation = translation + "B"
else:
translation = translation + letter
Otherwise you'll be hitting the else branch for every character other than Б (and that includes ㅏ!)
It might be worth noting that letter in "ㅏ" can be written more simply as letter == "ㅏ". The same goes for the other comparison.
Finally, you might also want to take a look at maketrans() and translate(): https://www.tutorialspoint.com/python3/string_maketrans.htm

Related

Issue with analyzing strings in Python for Wordle-esque progam

I've created a function that takes a user-inputted guess, compared it to a hidden word taken randomly from a word doc, and returns a string that indicates if any letters match or are in the word at all. Here is the function:
def wordResults(guess, testGuess):
#guess = user inputted guess
#testGuess = secret word
results = ""
for i in range(5):
#Check if letters at given position match
#in each word, append capital letter if so
if guess[i] == testGuess[i]:
results += guess[i].upper()
#Check if letter at given position is in
#the secret word at all, append lowercase
#letter if so
elif testGuess.find(guess[i]) != -1:
results += guess[i]
#Append underscore if neither condition is met
else:
results += "_"
return results
My issue lies with the elif-statement. I would like it to print a lowercase only if that letter appears in the word, but not if the letter is already in the correct spot. Here is the program running to show what I'm referring to:
(Note: the hidden word is also user-inputted until I get the program working as intended)
For Guess #2, I would like it so that the first 'h' does not show up, since it is indicating the 5th letter in 'conch' that is already confirmed with a capital 'H'. Hope that makes sense.
It's a lot easier to work with a list and then make it a string at the end:
guess = guess.lower()
testGuess = testGuess.lower()
result = []
for i, letter in enumerate(guess):
if letter in testGuess:
if letter == testGuess[i]:
result.append(letter)
else:
result.append(letter.upper())
else:
result.append('_')
for i, letter in enumerate(result):
if letter.upper() in result and result[i] != letter:
result[i] = '_'
return ''.join(result)
For guess two, then the second loop checks if each letter is already in the loop and placed correctly and if it's not in the correct spot, makes it back into an _.

Assigning empty quotes to a variable python

Why is the variable "translation" assigned to an empty string? Is that because we are going to replace it with the user's input?
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print (translate(input("Enter a phrase: ")))
In line 6 you have:
translation = translation + "G"
This tries to set translation to whatever string it previously was, but with G at the end. However, at the very start of the loop, what value is translation? How can we add something to it if it doesn't exist yet?
We need to initialize it so that things can be added onto it. That's what setting it to an empty string before the loop is doing.
You're appending "g" and "G" to it. If you don't initialize it, what would you be appending to? - Aplet123
You are doing + to the variable. if you don't initialize it, you'll get UnboundLocalError.
And if you initialize it in the for loop, it will keep resetting the value.
That's why you are assigning at the first part of the function.
And btw, you can use +=
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation += "G"
else:
translation += "g"
else:
translation += letter
return translation
print (translate(input("Enter a phrase: ")))
When a variable is assigned, it gets stored somewhere in the memory with an address. If you don't initialize(define) any location for data, how is it supposed to work?

string.lower() in an if loop doesn't lower case the string in Python?

def translate(phrase):
translation= ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
(This is a program to change vowels to the letter 'g' or 'G' depending if it is upper or lower case)
Why does this work? Since there is a letter.lower() shouldn't it transform that letter to a lowercase one? that way the next if statement ("if letter.isupper():") would never be true...
I'm confused because I only know C and I'm trying to learn Python. In C if I did that it would transform the letter variable to a lower case one so the next if statement would never be true. I'm guessing that functions inside if statements in Python don't change/alter the variables inside those same fucntions...? But then again that wouldn't really make sense to me... What am I thinking wrong?
From https://docs.python.org/3/library/stdtypes.html#str.lower:
Return a copy of the string with all the cased characters converted to lowercase.
letter.lower() does not modify letter when called, it returns a new value.

lower vs islower methods in if statements

def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "Q"
else:
translation = translation + "q"
else:
translation = translation + letter
return translation
print(translate(input("Enter phrase to translate: ")))
Hi, I'm new to Python and this is my first post here. I'm following a Python tutorial and I'm a little confused, this code executes fine, I'm just wondering why the following code works:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "Q"
If letter.lower converts each letter in sequence to a lower case, how could the next if statement return anything for letter.isupper?
If the phrase is "AaAa", wouldn't letter.lower() convert that to aaaa first, before checking the letter.isupper, meaning nothing could be isupper? Yet, it still works, and AaAa returns QqQq.
Also, is my formatting correct for posting the code on here? I just pasted it and clicked the bracket button.
Thanks
The lower method'1 only returns a lowercase letter (or the original string if there is no lowercase version); it does not change letter itself.
>>> letter = 'A'
>>> letter
'A'
>>> letter.lower()
'a'
>>> letter
'A"
lower() will return the lowercase character and you are checking if its a vowel. The letter itself is not changed e.g. A will remain as A
if letter.lower() in "aeiou":
The next line you are checking if its in upper case using isupper to add uppercase Q else lowercase q
if letter.isupper():
Don't get confused .I will make you very clear with your codes.
Please follow the steps below:-
1.your code:
if letter.lower() in "aeiou":
if letter.isupper():
translation=translation + "Q"
else:
translation=translation + "q"
In the first line of above code ,first of all you converted the letter(it can be in uppercase or lowercase) to lowercase.Then you checked that if it is in "aeiou" or not ,if the letter is there in "aeiou" then next if statement will get executed.
Now plese note that the letter you converted in the first line to lowercase remains in lowercase upto the execution of first line only,it means that the role of original case of the letter(case of letter while inputting it ) comes in account from second line,it also mean that the isupper() function do not change the case of the letter permanently.
3.According to your input "AaAa".First the letter 'A' will get converted into 'a' and as
'a' is there in "aeiou" control of program will go to second 'if' statement and there your letter is "A"(original case while input) so you get 'Q' as the result of 3rd statement and then this process continues for all letter("AaAa") and your output is "QqQq".
For more clarification of your doubt please refer to the code below and you will never stuck in this problem anymore:-
s="AaAa"
for letter in s:
print(letter.lower())
print(letter)
output:
a
A
a
a
a
A
a
a
ya you are correct with your formatting of code .You can post your question in a more better way but the way you have posted is also fine.

How can I get the index of a recurring character from a string?

I'm working with a hangman like project whereas if the user inputs a letter and matches with the solution, it replaces a specific asterisk that corresponds to the position of the letter in the solution. I'm trying to do this by getting the index of the instance of that letter in the solution then replacing the the matching index in the asterisk.
The thing here is that I only get the first instance of a recurring character when I used var.index(character) whereas I also have to replace the other instance of that letter. Here's the code:
word = 'turtlet'
astk = '******'
for i in word:
if i == t:
astk[word.index('i')] = i
Here it just replaces the first instance of 't' every time. How can I possibly solve this?
index() gives you only the index of the first occurrence of the character (technically, substring) in a string. You should take advantage of using enumerate(). Also, instead of a string, your guess (hidden word) should be a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct. You can then join() it when you want to display it. Here is a very simplified version of the game so you can see it in action:
word = 'turtlet'
guess = ['*'] * len(word)
while '*' in guess:
print(''.join(guess))
char = input('Enter char: ')
for i, x in enumerate(word):
if x == char:
guess[i] = char
print(''.join(guess))
print('Finished!')
Note the the find method of the string type has an optional parameter that tells where to start the search. So if you are sure that the string word has at least two ts, you can use
firstindex = word.find('t')
secondindex = word.find('t', firstindex + 1)
I'm sure you can see how to adapt that to other uses.
I believe there's a better way to do your specific task.
Simply keep the word (or phrase) itself and, when you need to display the masked phrase, calculate it at that point. The following snippet shows how you can do this:
>>> import re
>>> phrase = 'My hovercraft is full of eels'
>>> letters = ' mefl'
>>> display = re.sub("[^"+letters+"]", '*', phrase, flags=re.IGNORECASE)
>>> display
'M* ***e****f* ** f*ll *f eel*'
Note that letters should start with the characters you want displayed regardless (space in my case but may include punctuation as well). As each letter is guessed, add it to letters and recalculate/redisplay the masked phrase.
The regular expression substitution replaces all characters that are not in letters, with an asterisk.
for i in range(len(word)):
if word[i] == "t":
astk = astk[:i] + word[i] + astk[i + 1:]

Categories

Resources