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]
Related
If I write an input like 'I like apples' then I want the output to be I.L.Apples, but I keep getting I.L.A.Apples. Can anyone help me on removing the 'A.' part?
user_input = input('Enter a sentence: ')
sentence = user_input.split()
a = ""
b = ""
lastword = user_input.split()[-1]
for i in sentence:
a = a + str(i[0]).upper() + '.'
b = lastword.title()
print(a+b)
This looks like a homework problem, so I don't think I should give you the answer. But some thoughts.
Why are you setting "b" inside your loop, rather than outside it?
You are looping over all the words in the sentence adding their initials. Don't you think you should be looping over all the words in the sentence except the last one?
I'm trying to write a small program for my python course(teaching myself), kinda like a dictionary using lists. One list has a phrase/word in it and the other list has the meaning of the phrase/word. Through user input the user can type the word they are searching for and the words meaning would be shown. I'm having trouble trying to get the meaning to be shown. My code is below: "aldo" is my first input(word), "my name" is my second input(meaning)
word = []
meaning = []
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
print(word)
print(meaning)
word = word + [user_word]
meaning = meaning + [user_meaning]
user_search = input("What word/phrase would you like to search: ")
search_index = word.index(user_search)
print(user_search + meaning.index(search_index))
There are a few bugs/issues in your code.
Printing empty lists, not sure if this is intended as a check for debugging but you are printing the lists before appending values to them, so they will always be empty. So I'm assuming you want to print the user's input here; if not then first append the values and then print the lists.
Use list.append(item) instead of list = list + [item]
meaning.index(search_index) should be meaning[search_index] as list.index(item) returns index value for the first occurrence of that item in the list and not the value itself.
Lastly, not very important but more of a readability issue, make sure there is a space between the word and the meaning or some kind of deliminator.
Here's the code assuming the expected behaviour:
word = []
meaning = []
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
print(user_word)
print(user_meaning)
word.append(user_word)
meaning.append(user_meaning)
print(word)
print(meaning)
user_search = input("What word/phrase would you like to search: ")
print(user_search)
search_index = word.index(user_search)
print(user_search, meaning[search_index])
.index() finds an index, not a value
Did you mean to use meaning[search_index]?
Also, to add to lists, using .append(value) is preferred over + [value]
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
word.append(user_word.strip())
meaning.append(user_meaning)
user_search = input("What word/phrase would you like to search: ")
search_index = word.index(user_search.strip())
print(user_search + " " + meaning[search_index])
If you are trying to create dictionary, instead of list you can use dictionary to store words and meaning and later use it for searching word (for learning more about dictionary, you can look into documentation).
You can try following:
my_dictionary = {} # dictionary to store word and meaning
user_word = input("Enter word: ").lower() # .lower() for not being case sensitive
user_meaning = input("Enter Meaning: ").lower() # .lower()
# add word and meaning to dictionary
my_dictionary[user_word] = user_meaning
# search word
user_search = input("What word/phrase would you like to search: ").lower()
print("Meaning of {0} is: {1}".format(user_search, my_dictionary[user_search]))
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)
I need the code to ask the user to enter a word and print them out in a sentence once stop is entered. I have the following code:
`a = input("Enter a word: ")
sentence = ()
while a != ("stop"):
sentence = sentence , a
a = input("Enter a word: ")
print (sentence)`
However I don't know how to set the variable 'Sentence' so that nothing prints at the start. How can I rectify this?
In order to get a string, you need to use raw_input() instead input() (input saves as int, double etc...).
Replace input() to raw_input().
In addition, sentence = () - saves tuple and sentence = sentence , a - adds more tuples and not a string as i think you want.
Try to explain again what you mean.
You can try the following:
a = input("Enter a word: ")
sentence = ""
while a != "stop":
sentence = sentence + " " + a
a = input("Enter a word: ")
print (sentence)
input (raw_input in python 2) will allow you to write strings without the need for quotes. Sentence has to be initialized to an empty string "", and concatenated as a string (here with a simple + ).
I Am writing a function that should take a string input and return the string with every first letter of every word as a capital letter, I have achieved this to a certain degree.
My Code:
string = input("Please Enter A string:")
def capitalize_words(string):
split = string.split()
letter1 = ''
letter2 = ''
letter3 = ''
str1 = split[0]
str2 = split[1]
str3 = split[2]
for i in str1:
if i in str1[0]:
first = i.upper()
else:
letter1 = letter1 + i
string1 = (first+letter1)
for i in str2:
if i in str2[0]:
first = i.upper()
else:
letter2 = letter2 + i
string2 = (first+letter2)
for i in str3:
if i in str3[0]:
first = i.upper()
else:
letter3 = letter3 + i
string3 = (first+letter3)
result = string1+' '+string2+' '+string3
return result
func = capitalize_words(string)
print(func)
Input:
Please Enter A string:herp derp sherp
Output:
Herp Derp Sherp
However this is very inflexible because i can only enter 3 words with spaces no more no less , this makes for a rather primal program. I would like to be able to enter anything and get the desired result of the first letter of every word being a capital letter no matter how many words i enter.
I fear with my skills this is as far as I am able to get, can you please improve my program if possible.
>>> print(raw_input('Please Enter A string: ').title())
Please Enter A string: herp derp sherp
Herp Derp Sherp
Use str.title() to achieve what you want in one go.
But to process words in a sentence, use a loop instead of a series of local variables; here is a version that does the same what you are doing for an arbitrary number of words:
for i, word in enumerate(split):
split[i] = word[0].upper() + word[1:]
result = ' '.join(split)
I used string slicing as well to select just the first character, and all but the first character of a word. Note the use of enumerate() to give us a counter which wich we can replace words in the split list directly.
An alternative method is to use re.sub such as:
re.sub(r'\b.', lambda c: c.group().upper(), 'herp derp sherp and co.')
# 'Herp Derp Sherp And Co.'
You could write this in a one-line generator expression:
def upper_case(text):
return ' '.join(w[0].upper() + w[1:] for w in text.split())
Notice, that this function fails on single letter words and replaces any whitespace by a single space character.
Use this as
In [1]: upper_case(input('Please Enter A string: '))
Please Enter A string: hello world
Out[1]: 'Hello World'