I want to be able to pick out certain letters in a string but need to be able to get the place of multiple rather then just the first (Python). I currently have this code:
word=apple #just and example
character=input("Take a guess")
if character == "a":
place=word.find("a")
elif character == "b":
place=word.find("b")
elif character == "c":
place=word.find("c")
elif character == "d":
place=word.find("d")
elif character == "e":
place=word.find("e")
elif character == "f":
place=word.find("f")
elif character == "g":
place=word.find("g")
elif character == "h":
place=word.find("h")
elif character == "i":
place=word.find("i")
elif character == "j":
place=word.find("j")
elif character == "k":
place=word.find("k")
elif character == "l":
place=word.find("l")
elif character == "m":
place=word.find("m")
elif character == "n":
place=word.find("n")
elif character == "o":
place=word.find("o")
elif character == "p":
place=word.find("p")
elif character == "q":
place=word.find("q")
elif character == "r":
place=word.find("r")
elif character == "s":
place=word.find("s")
elif character == "t":
place=word.find("t")
elif character == "u":
place=word.find("u")
elif character == "v":
place=word.find("v")
elif character == "x":
place=word.find("w")
elif character == "w":
place=word.find("x")
elif character == "y":
place=word.find("y")
else:
place=word.find("z")
This works to find the place of one letter, but if I wanted to find both p's it wouldn't work, it'd only tell me the position of the first. So what I'm really wondering is if there is some loop I can put it through to find the letters and set them as two different variables such as "place" and "place2" or do I have to have this same thing multiple different times for each separate starting point.
You can use re.finditer() to get all occurrences of the substring:
>>> import re
>>> word = "apple" #just and example
>>> character = input("Take a guess: ")
>>> for occurrence in re.finditer(character, word):
... print('character: {}, {}'.format(character, occurrence.start()))
Regular expressions are a powerful tool. However, there is a considerable overhead in using regexps for a trivial string literal search.
Here is a simple alternative repeatedly calling str.find until all occurrences are found:
def findall(mainstring, substring):
pos = -1
while True:
pos = mainstring.find(substring, pos+1)
if pos == -1:
break
yield pos
for occurence in findall("apple", "p"):
print(occurence)
# prints: 1 2
Related
I got stuck on this question on the Cisco training. I got to the answer, but don't understand why it works. Why does python remove the vowels after each 'continue'?
user_word = input("Enter your word: ")
user_word = user_word.upper()
for i in user_word:
if i == "A":
continue
elif i == "E":
continue
elif i == "I":
continue
elif i == "O":
continue
elif i == "U":
continue
else:
print(i)
It does not "remove" them, it just does not print() them.
The loop is executed for each character in the word. If it is a vowel, the current iteration is ended (see the continue statement) and the next character is considered. If it is NOT a vowel, it is printed to the output and you can "see" it.
The reason for this is as follows:
contunue means skip the loop, in fact it is this:
The continue statement, also borrowed from C, continues with the next iteration of the loop
So any vowel a, e, i, o, u gets skipped and any consonant is printed.
by way of example, if you replace the continue keyword with your own function you would see this more clearly:
user_word = input("Enter your word: ")
user_word = user_word.upper()
# a new function to replace continue
def replace_continue():
print('vowel is found')
for i in user_word:
if i == "A":
replace_continue()
elif i == "E":
replace_continue()
elif i == "I":
replace_continue()
elif i == "O":
replace_continue()
elif i == "U":
replace_continue()
else:
print(i)
try this code and it should be more obvious.
Here is a link to the docs:
https://docs.python.org/3/tutorial/controlflow.html
The vowels do not get removed as in deleted, they just get ignored. continue is a key word, which tells the loop to go to the next iteration. If you were to put another print in the loop, outside of the if/elif statements, it becomes more visible. You may want to check the documentation for further information
for i in user_word:
if i == "A":
continue
elif i == "E":
continue
elif i == "I":
continue
elif i == "O":
continue
elif i == "U":
continue
else:
print(i)
print('loop end')
Using the wourd 'continous' as value the above code yields :
C
loop end
N
loop end
T
loop end
N
loop end
S
loop end
The code should replace all the vowels with the letter p. How come this code works. If I input "hello" it prints "hpllp"
for i in word:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
word = word.replace(i, "p")
print(word)
But this doesn't? It prints out "hellp"
translated_word = ""
for i in word:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
translated_word = word.replace(i, "p")
print(translated_word)
TYIA
In the first code you were setting the variable "word" to itself while performing replacements.
In the second you were setting the "translated_word" variable equal to the "word" replacement but without a way for the code to remember that in between loops and being constantly overwritten as the loop went on.
Depending on the use a function can be used with fairly little change to your current code.
def replace(word):
for i in word:
if i == "a" or i == "e" or i == "i" or i == "o" or i == "u":
word = word.replace(i, "p")
return(word)
translated_word = replace('hello')
print(translated_word)
This is my code and I made it say "Please enter the right letter next time." when the incorrect base is inputted to the code, it does that it like:
Please enter the right letter next time.
None
How can I remove the "None" from appearing when ran?
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return print("Please enter the right letter next time.")
#main program
base1 = match_base("X")
print(base1)
It's because you're trying to return a print statement which doesn't make any sense.
Please change to:
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return "Please enter the right letter next time."
#main program
base1 = match_base("X")
print(base1)
If you don't want to recover, use an exception.
def match_base(base):
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
raise ValueError("Please enter the right letter next time.")
If you do want to recover, let the caller do the work:
def match_base(base):
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return None
base1 = match_base("X")
if not base1:
print("Please enter the right letter next time.")
else:
print(base1)
Note that this would be easier with a dictionary:
maps = {'A':'T', 'T':'A','C':'G','G':'C'}
def match_base(base):
return maps.get(base, None)
The reason you are getting None is because your program is trying to assign the print statement to a variable. print("Please enter the right letter next time.") cannot be a stored in a variable.
So it should look like this instead:
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
print("Please enter the right letter next time.")
I really cant figure out what's the problem here.
def winner(board, letter):
#below is the winning combination. If any of the combination matches the winner is gonna be declared
(board['top-L'] == letter and board['top-M'] == letter and board['top-R'] == letter) **or**
(board['low-L'] == letter and board['low-M'] == letter and board['low-R'] == letter) or
(board['mid-L'] == letter and board['mid-M'] == letter and board['mid-R'] == letter) or
(board['top-L'] == letter and board['mid-L'] == letter and board['low-L'] == letter) or
(board['top-M'] == letter and board['mid-M'] == letter and board['low-M'] == letter) or
(board['top-R'] == letter and board['mid-R'] == letter and board['low-R'] == letter) or
(board['top-L'] == letter and board['mid-M'] == letter and board['low-R'] == letter) or
(board['top-R'] == letter and board['mid-M'] == letter and board['low-L'] == letter) or
I am using python to create a text to binary translator, I checked everything and it seems alright but when I execute it, the program only prints the first letter of the text. Here's the code:
if beep == 1:
letter = letter + 1
if letter > length:
beep = 2
if list1[letter] == "a":
print abinary
elif list1[letter] == "b":
print bbinary
elif list1[letter] == "c":
print cbinary
elif list1[letter] == "d":
print dbinary
elif list1[letter] == "e":
print ebinary
elif list1[letter] == "f":
print fbinary
elif list1[letter] == "g":
print gbinary
elif list1[letter] == "h":
print hbinary
elif list1[letter] == "i":
print ibinary
elif list1[letter] == "j":
print jbinary
elif list1[letter] == "k":
print kbinary
elif list1[letter] == "l":
print lbinary
elif list1[letter] == "m":
print mbinary
elif list1[letter] == "n":
print nbinary
elif list1[letter] == "o":
print obinary
elif list1[letter] == "p":
print pbinary
elif list1[letter] == "q":
print qbinary
elif list1[letter] == "r":
print rbinary
elif list1[letter] == "s":
print sbinary
elif list1[letter] == "t":
print tbinary
elif list1[letter] == "u":
print ubinary
elif list1[letter] == "v":
print vbinary
elif list1[letter] == "w":
print wbinary
elif list1[letter] == "x":
print xbinary
elif list1[letter] == "y":
print ybinary
elif list1[letter] == "z":
print zbinary
else:
print "error."
Anyone know what is going on, I am fairly knew but I cant find this in any of my books.
If you want the code to run multiple times, you need to use a loop:
while beep == 1:
if list1[letter] == "a":
print abinary
...
letter = letter + 1
if letter >= length(list):
beep = 2
You can even do this more beautiful using a for-loop to iterate over all letters in your list:
for letter in list1:
if letter == "a":
print abinary
...
instead of chaining alot of elifs you should store the binary representation of the letters in a dictionary:
binary_letters = {
"a": "01100001",
"b": "01100010",
...
"z": "01111010"
}
this will simplify the loop to:
for letter in list1:
print binary_letters[letter]
The for loop that you can implement it as follows, you can even convert the letters to a binary string:
letter="k"
for n in range(97,123):
if ord(letter)<97 or ord(letter)>123:
#if character is not between 97-123 (a-z) print an error message
print("Error:Not in range")
break
#print(n)
if n==ord(letter):
#print the binary string if character is between the codes 97-123 (a-z)
print(format(ord(letter),'b'))