word = hello
dashes = '-' * len(word)
guess = input()
If guess is h I want to replace dashes[0] with h because h is word[0] how would I check to see if h is in word, and then if it is, replace the appropriate - in dashes at the index guess is in word
Then given another input() and dashes is now h---- and the input is l do the same but so that dashes becomes h-ll-
I hope this makes sense, best I can explain it.
I have tried the following after a guess is made and before another guess is given:
dashes = dashes.replace(dashes[word.index(guess)], guess)
but if guess is h, dashes becomes hhhhh
not sure why or how to fix it.
str.replace replaces every instance of - in dashes.
You can instead iterate through the dashes after zipping with the full word and replace only the character in the same position(s) as the correct guess:
dashes = ''.join(j if j==guess else i for i, j in zip(dashes, word))
def update_blanks(guess, dashes):
return ''.join(j if j==guess else i for i, j in zip(dashes, word))
guess = 'h'
dashes = update_blanks(guess, dashes)
print(dashes)
# h----
guess = 'l'
dashes = update_blanks(guess, dashes)
print(dashes)
# h-ll-
I guess this is a 'hangman-esque' game. Try this.
word = 'hello'
current = ['-']*len(hello)
guess = input()
for i in range(len(word)):
if word[i] == guess:
current[i] = word[i]
This is more efficient if you are planning to continuously update the current state of your guesses.
Since string is immutable - I will decompose the word into a list of characters, replace suitable - and then compose into a word again
word_chars = [guess if c == '-' and word[i] == guess else c
for i, c in enumerate(dashes)]
dashes = ''.join(word_chars)
Related
As the title says, the output contains some uppercase letters, but for the life of me I can't figure out why. <=== Read the entire post to understand the problem. This is the code snippet which I'm assuming causes the 'error'.
def translate(s):
i = 0
word = ""
for letter in s:
word += letter.upper() + (letter * i) + "-"
i += 1
The function takes a string as input and returns a string with first letter being capital and the following letters being multiplied by 1 += 1 (+1 for each set of different letters), followed by "-".
Example:
Input and Output
Input: "ZpglnRxqenU"
Expected Output: "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"
Actual Output: "Z-Pp-Ggg-Llll-Nnnnn-RRRRRR-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-UUUUUUUUUUU"
The problem
As you can see, the R:s are all uppercase and so is the U:s. My question is: Why are they uppercase? I know why the first letter is, and that's intended but there should never be more than one uppercase (the first letter) per section (a section being within the bounderies of "-" and "-").
For further refrence: https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/
OBS: I'm not doing this to get an answer to the codewars challenge.
This is the entire code.
def translate(s):
i = 0
word = ""
for letter in s:
word += letter.upper() + (letter * i) + "-"
i += 1
eq1 = list(word)
eq1.reverse()
eq1.remove("-")
eq1.reverse()
word = ""
for y in eq1:
word += y
return word
Lines 7-12 are just my way of dealing with removing the last "-". The output would have an "-" at the end if it wasn't there. I know it's a bad way of dealing with it but I just wanted to finish it as fast as possible.
The R's and U's are uppercase because in the initial string, they are uppercase. They will stay uppercase unless you try to change them to lowercase.
Here is your updated code:
def translate(s):
i = 0
word = ""
for letter in s:
word += letter.upper() + (letter.lower() * i) + "-"
i += 1
Notice the .lower() after letter in (letter * i).
The R:s and U:s are uppercase because we multiply the first letter of the given character. It totally slipped my mind that the character may be uppercase and therefor the multiplies of the letter will too be uppercase.
I have been asked to create a simple word guessing game that will select a random word from a list, but then displays that word with every alternate letter replaced with a hyphen.
I have figured out the selection of the random word, but after that I don't have any idea.
The prompt does mention using the modulus operator (%) within a for-loop to detect if a letter's position is odd or even, which I understand to an extent, but I cant figure out how to make it work in this case.
Code using a for loop in Python:
word = "Python" #Add your code for random words instead
ans = ""
for i in range(len(word)):
if i%2 != 0:
ans += "-"
else:
ans += word[i]
print(ans)
Output:
P-t-o-
You could get letters at even positions using a striding subscript (word[::2]) and join them with an hyphen. Make sure to have an extra space for the last letter in case the word has an even number of letters.
word = "Elephant"
hyphened = "-".join((word+' ')[::2])
print(hyphened)
E-e-h-n-
This solution is even simpler than a for loop:
original_word = "alternate" #generate a word
word = list(original_word) #split the string in chars
word[1::2]=["-"]*len(word[1::2]) #replace chars in odd positions with '-'
print(original_word)
print("".join(word))
Hope this is useful.
I'm trying to make a program that will convert any text into a different form. That means that a text such as 'hi there' becomes 'hI tHeRe'.
list = []
word = input('Enter in a word or a sentence! ')
for num in range(len(word)):
list.clear()
list.append('i')
letter = word[num]
for x in range(len(list)):
if x % 2 == 0:
i = word.index(letter)
place = letter.lower()
word = word.replace(word[i], place)
if not x % 2 == 0:
i = word.index(letter)
place = letter.upper()
word = word.replace(word[i], place)
print(word)
However, when I run the code it just prints the same string as normal.
When using replace, you have to assign the result to your variable:
word = word.replace(word[i], place)
However, replace is actually not what you want here. replace replaces all instances of a certain pattern with a new string. In your current code, every instance of whatever letter word[i] represents will be replaced with the result of .lower() or .upper().
You also don't want to use the word list, since doing so will shadow the Python built-in list class.
If you want to keep most of your original logic, you can follow #khelwood's suggestion in the comments and end up with the following:
word = input('Enter in a word or a sentence! ')
wordList = list(word)
for i in range(len(word)):
if i % 2 == 0:
wordList[i] = word[i].lower()
else:
wordList[i] = word[i].upper()
print(''.join(wordList))
Here is one of my previous codes, you can change all the variable names to whatever you see fit.
s = input('Enter in a word or string.')
ret = ""
i = True # capitalize
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
print(ret)
I hope it works for you.
Try this one liner -
a = 'hi there'
''.join([i[1].lower() if i[0]%2==0 else i[1].upper() for i in enumerate(a)])
'hI ThErE'
If you care about each word starting from lowercase then this nested list comprehension works -
' '.join([''.join([j[1].lower() if j[0]%2==0 else j[1].upper() for j in enumerate(i)]) for i in a.split()])
'hI tHeRe'
The problem is with list.clear in the beginning of the for loop.
Each iteration you clear the list so the second for iteration run on the first item only.
Remove list.clear and it should scan the input word
I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code.
import random
import urllib.request
wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-
type=text/plain"
response = urllib.request.urlopen(wp)
long_txt = response.read().decode()
words = long_txt.splitlines()
###########
# Methods #
###########
def Run():
dashes1 = "-" * len(word)
dashes2 = "-" * len(word2)
used_letter = []
dashes = dashes1 + " " + dashes2
#dashes ="-" * len(secretWord)
guessesLeft = 6
while guessesLeft > -1 and not dashes == secretWord:
print(used_letter)
print(dashes)
print (str(guessesLeft))
guess = input("Guess:")
used_letter.append(guess)
if len(guess) != 1:
print ("Your guess must have exactly one character!")
elif guess in secretWord:
print ("That letter is in the secret word!")
dashes = updateDashes(secretWord, dashes, guess)
else:
print ("That letter is not in the secret word!")
guessesLeft -= 1
if guessesLeft < 0:
print ("You lose. The word was: " + str(secretWord))
print(dashes)
else:
print ("Congrats! You win! The word was: " + str(secretWord))
print(dashes)
def updateDashes(secret, cur_dash, rec_guess):
result = ""
for i in range(len(secret)):
if secret[i] == rec_guess:
result = result + rec_guess
else:
result = result + cur_dash[i]
return result
########
# Main #
########
word = random.choice(words)
word2 = random.choice(words)
#print(word)
#print(word2)
secretWord = word + " " + word2 # can comment out the + word2 to do one
word or add more above to create and combine more words will have to adjust
abouve in Run()
splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)])
print (splitw)
Run()
any bit of help is appreciated. The website I'm using has a bunch of words that are being used for the words randomly generated. Some are capitalized, and I need to figure out how to let the input of a letter, say a capital A, accept a lowercase a and count for it.
you could compare after you converted everything to lowercase.
e.g. you could do
secretWord = word.lower() + " " + word2.lower() # that should make your secret all lowercase
for the input you should do the same:
guess = input("Guess:").lower()
after that it should not matter if it is upper or lower case. it should always match if the letter is the correct one.
hope that helps
Simply check everything in lowercase:
[...]
elif guess.lower() in secretWord.lower():
[...]
and so on.
I would just change this line:
while guessesLeft > -1 and not dashes == secretWord:
to:
while guessesLeft > -1 and not dashes.lower() == secretWord.lower():
This way you are always comparing lower-case representations of the user's input to the lower-case representation of your secretWord. Since this is the main loop for your game, you want to break out of this as soon as the user's guess matches your word regardless of case. Then later in your code, you will still check whether they had any guesses left, and print out their answer and the secret word as before.
No other changes required, I think.
You could just force all comparisons to be made in the same Case, such as lowercase.
Let’s say that your word is "Bacon". and someone enters "o".
That will be a match because quite obviously “o” equals “o” so you can cross that letter off the list of letters left to guess.
But in the case that someone enters “b” then b is NOT equal to “B”.
So why not just force all letters to be compared using the same case?
So your comparison will be like
elif guess.Lower() in secretWord.Lower()
My python is rusty as hell, but the idea here should do what you want to do
I tried to run this program, but for some reason the string gets changed only to lowercase. The vowels don't turn to lowercase. Any ideas on why?
Thanks!
def changeCaps(string):
i = 0
while i < len(string):
if string[i] == 'a' or string[i] == 'e' or string[i] == 'i' or string[i] == 'o' or string[i] =='u':
print(string[i].upper())
i = i + 1
else:
print(string[i].lower())
i = i + 1
changeCaps("AlbErT")
What doubleo said in his two comments is correct: because the A and E in AlbErt are already capitalized, they aren't equal to lowercase a and e, and as such, they are made to be lowercase along with all the consonants. if you ware wanting to change the case of any letter typed, that would require a different routine. Something more along these lines:
def changeCaps(string):
i = 0
while i < len(string):
if string[i].islower():
print(string[i].upper())
i = i + 1
else:
print(string[i].lower())
i = i + 1
changeCaps("AlbErT")
This will result in any uppercase letters becoming lowercase and any lowercase letters becoming uppercase, and whether or not it is a vowel or consonant will have nothing to do with it.
Also, why not use a for loop instead? This will work just as well, and take up fewer lines of code:
def changeCaps(string):
for i in range(len(string)):
if string[i].islower():
print(string[i].upper())
else:
print(string[i].lower())
changeCaps("AlbErT")
Okay, so it only saves two lines, but it makes more sense to use a for loop in my opinion. Either way, the resultant output would be:
aLBeRt
On a final note, as Anton pointed out, you don't even really need a numeric pointer, just go over the string.
def changeCaps(string):
for c in string:
if c.islower():
print(c.upper())
else:
print(c.lower())
changeCaps("AlbErT")
(Thanks, Anton!)