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?
Related
I have the following code
def pig(text):
message = text.split()
pig_latin = []
for word in message:
word = word[1:] + word[0] + 'ay'
pig_latin.append(word)
return ' '.join(pig_latin)
def main():
user = str(input("Enter a string: "))
print(f"Pig latin: {pig(user)}")
Input: Practice makes perfect
Expected Output: Racticepay akesmay erfectpay
My translator is working fine, but I need to capitalize only the first letter of every sentence.
I can't figure out where to place the .capitalize() to get my desired output. I have put it in many locations and no luck so far.
In addition to what #BrokenBenchmark said, a format string and a generator expression would simplify your code down to a single, readable line of code.
def pig(text):
return ' '.join(f"{w[1:]}{w[0]}ay" for w in text.split()).capitalize()
Capitalizing should be the last thing you do before you return, so put .capitalize() at the return statement.
Change
return ' '.join(pig_latin)
to
return ' '.join(pig_latin).capitalize()
Just had to restart VS code now it works lol
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:])
Need to find the longest word in a string and print that word.
1.) Ask user to enter sentence separated by spaces.
2.)Find and print the longest word. If two or more words are the same length than print the first word.
this is what I have so far
def maxword(splitlist): #sorry, still trying to understand loops
for word in splitlist:
length = len(word)
if ??????
wordlist = input("Enter a sentence: ")
splitlist = wordlist.split()
maxword(splitlist)
I'm hitting a wall when trying to compare the lenghts of words in a sentance. I'm a student who's been using python for 5 weeks.
def longestWord(sentence):
longest = 0 # Keep track of the longest length
word = '' # And the word that corresponds to that length
for i in sentence.split():
if len(i) > longest:
word = i
longest = len(i)
return word
>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'
You can use max with a key:
def max_word(splitlist):
return max(splitlist.split(),key=len) if splitlist.strip() else "" # python 2
def max_word(splitlist):
return max(splitlist.split()," ",key=len) # python 3
Or use a try/except as suggested by jon clements:
def max_word(splitlist):
try:
return max(splitlist.split(),key=len)
except ValueError:
return " "
You're going in the right direction. Most of your code looks good, you just need to finish the logic to determine which is the longest word. Since this seems like a homework question I don't want to give you the direct answer (even though everyone else has which I think is useless for a student like you), but there are multiple ways to solve this problem.
You're getting the length of each word correctly, but what do you need to compare each length against? Try to say the problem aloud and how you'd personally solve the problem aloud. I think you'll find that your english description translates nicely to a python version.
Another solution that doesn't use an if statement might use the built-in python function max which takes in a list of numbers and returns the max of them. How could you use that?
You can use nlargest from heapq module
import heapq
heapq.nlargest(1, sentence.split(), key=len)
sentence = raw_input("Enter sentence: ")
words = sentence.split(" ")
maxlen = 0
longest_word = ''
for word in words:
if len(word) > maxlen:
maxlen = len(word)
longest_word = word
print(word, maxlen)
So for some background: I've been going through learning python the hard way and have taken a little break to try doing a few fun things, I came across on a suggestion on daniweb, to try create a program in which you enter in a list of characters and it will then print out any word that contain all those characters.
I've figured out how to do it manually, here's the below code:
string = raw_input("Please enter the scrable letters you have: ")
for line in open('/usr/share/dict/words', 'r').readlines():
if string[0] in line and string[1] in line and string[2] in line:
print line,
But I somehow cannot figure out how to get it to work by using loops (that way the user can enter in a list of characters of any length. I figured something like the below would work, but it doesn't appear to do so:
while i < len(string)-1:
if string[i] in line: tally = tally + 1
i = i + 1
if tally == len(string)-1: print line
else: i = 0
Any help in the right direction would be much appreciated, thanks.
I would use all with a comprehension for this ... and the comprehension is a loop
user_string = raw_input("Please enter the scrable letters you have: ")
for line in open('/usr/share/dict/words', 'r').readlines():
if all(c in line for c in user_string):
print line,
Set operations can come in handy here:
inp = set(raw_input("Please enter the scrable letters you have: "))
with open('/usr/share/dict/words', 'r') as words:
for word in words:
if inp <= set(word):
print word,