For my comp sci class I was assigned to make an english to pirate dictionary. The user is prompted to enter a sentence which is then translated to pirate but it isn't working and I'm not sure why. Any help would be appreciated.
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate: ")
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
print(b)
Your loop is iterating over range(len(a)), so x will take on an integer value for each individual character in your input. This is off for a couple of reasons:
Your goal is to iterate over words, not characters.
Indexing the dictionary should be done with words, not integers (this is the cause of your error).
Finally, note that .replace() replaces the first occurrence of the searched item in the string. To revise your approach to this problem in a way that still uses that method, consider these two main changes:
Iterate over the keys of the dictionary; the words that could potentially be replaced.
Loop until no such words exist in the input, since replace only does individual changes.
You're iterating over each of the characters in the string input, as the other answer before this has said, replace only replaces the first occurence.
You'd want to do something like this (after you've made your dictionary).
a = input("Please enter a sentence to be translated into pirate: ")
for x in eng2pir:
while x in a:
a = a.replace(x,eng2pir[x])
print(a)
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
because for loop x is int
but eng2pir dict no int key
so output error
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate:\n ")
lst = a.split()
b = ''
for word in lst:
b += eng2pir.get(word, "")
print(b)
Related
I am writing a program that takes a statement or phrase from a user and converts it to an acronym.
It should look like:
Enter statement here:
> Thank god it's Friday
Acronym : TGIF
The best way I have found to accomplish this is through a list and using .split() to separate each word into its own string and am able to isolate the first letter of the first item, however when I try to modify the program for the following items by changing to print statement to:
print("Acronym :", x[0:][0])
it just ends up printing the entirety of the letters in the first item.
Here's what I have gotten so far, however it only prints the first letter of the first item...
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
print("Acronym :", x[0][0])
Using re.sub with a callback we can try:
inp = "Peas porridge hot"
output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
print(output) # PPH
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
result = ''
for i in x:
word = list(i)
result+=word[0]
print(result)
The code needs to iterate through the .split result. For example, using a list comprehension:
inp = "Thank god its friday"
inp = inp.split()
first_lets = [word[0] for word in inp]
I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])
So I'm making a A1Z26 cipher decoder where I could enter the numbers in and it'll return a corresponding letter, e.g. 8,5,12,12,0 --> h,e,l,l,o.
However, I'm having trouble figuring out how to make python take each number as input as opposed to splitting them into digits.
Any help would be appreciated. Thanks
EDIT:
Here's the code I've written so far:`
dic = {dictionary that translates numbers to letters}
mid = []
output = []
input = raw_input("Enter the code here: ")
splitinput = list(input)
for i in splitinput:
if i != ",":
mid.append(i)
mid = [int(i) for i in buffer]
for i in mid:
output.append(dic[i])
print output
So for it to stop splitting each number into digits I would need to use something other than the list function.
Something like this:
myint = 123456789
mystr = str(myint)
print(','.join(mystr[::2]))
Alright, I found it. This is the code that gives me the desired output if anyone will be interested:
inv_alphabet = {contains the mapping of each number to letter}
output = []
code_input = str(raw_input("Enter your cipher here: "))
split_code = code_input.split(",")
split_code = [int(i) for i in split_code]
for i in split_code:
output.append(inv_alphabet[i])
print output
I'm working a question where I need to create a program that will ask the user to input a list and then it will print off the strings that start with letters A-I.
Question: Implement a program that asks for a list of student names from
the user and prints those names that start with letters A through I.
Create two test lists.
>>> phrase = input('Enter a list of Students: ')
Enter a list of Students: ['Albert', 'Ian', 'Bob', 'Dave', 'Edward']:
>>> for c in phrase:
if c in 'abcdefghiABCDEFGHI':
print(c)
Right now the print function results in:
A
b
e
I
a
B
b
D
a
e
E
d
a
d
It prints off letters in each of the name in alphabetical order, but what I want it do do is print off the entire names in alphabetical order. Once I can do it for one list, a 2nd list shouldn't be an issue.
To only print out the names that start with those letters you just need to index the first character c[0], e.g.:
phrase = input("Enter list of students")
for name in phrase:
if name[0] in 'ABCDEFGHI':
print(name)
Just be aware input() is generally considered unsafe because arbitrary code can be executed. A safer, but probably unnecessary at this level, approach would be:
import ast
phrase = ast.literal_eval(raw_input("Enter list of students"))
for name in phrase:
if name[0] in 'ABCDEFGHI':
print(name)
See my comment above, the phrase is a string when you input it. You have yet to make it into a list.
Try:
phrase = eval(input("Enter list of students")) #this evaluates the list put in
for names in phrase:
for letters in names:
if letters in 'abcdefghiABCDEFGHI':
print(names)
Next up
phrase = eval(input("Enter list of students"))
i = 0
while i < len(phrase): #for each item in phrase up to the end!
for letters in phrase[i]
if letters in 'abcdefghiABCDEFGHI':
print phrase[i]
phrase.pop(i)
i-=1 #set i backwards (as the incrementer downstairs will set it back to normal"
break #get out of this loop only one print please
i+=1 #fast way to increment
So I'm quite new to Python and am trying to create a program to identify 'super anagrams' i.e anagrams that have the same first and last letters. I came up with this, and it works, but I've got this feeling that there's a cleaner way to do it. Any ideas? Cheers.
words = input('Enter words: ')
listed = words.split()
first = listed[0]
second = listed[1]
first_split = (list(first))
second_split = (list(second))
if first_split[0]==second_split[0] and first_split[-1]==second_split[-1]:
first_split_alpha = sorted(first_split)
second_split_alpha = sorted(second_split)
if first_split_alpha == second_split_alpha:
print('Super Anagram!')
else: print('Huh?')
else: print('Huh?')
1) The temporary variable listed is unnecessary. Use tuple unpacking to get the values
2) The use of list is unnecessary. str is an iterable object, too.
3) The use of _alpha is unecessary. Just use sorted(foo) in your expression.
a,b = input('Enter words: ').split()
if sorted(a) == sorted(b) and a[0] == b[0] and a[-1] == b[-1]:
print('Super Anagram!')
else:
print('Huh?')
One suggestion I would make would be to check that the input contains exactly two words. Your code would throw an exception if the user were to enter just one word. You might do this by:
words = [] # empty list
while len(words) != 2:
words = input('Enter two words: ').split()
Following that, you could reduce the number of distinct variables you create. If you create a variable and then only use it once, chances are that you could inline whatever you are doing with that variable:
first = words[0]
second = words[1]
if (first[0] == second[0] and
first[-1] == second[-1] and
sorted(first) == sorted(second)):
print('Super Anagram!')
else:
print('Huh?')