Capitalizing first letter in split-append-join operation - python

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

Related

How do I only change first letter into a capital using ascii in python

The code I currently have makes it so that the entire word is capitalised instead of just the first letter which is what I am trying to accomplish.
https://i.stack.imgur.com/4FgE7.png
There is a nice method for str called .capitalize()
word = "hello"
word.capitalize()
word = "pinklemon1998"
_word = word[0].upper() + word[1:]
Or as mentioned in the comments:
_word = word.title()

Why does str.capitalize() not work as I expect?

Please, let me know if I'm not providing enough information. The goal of the program is to capitalize the first letter of every sentence.
usr_str = input()
def fix_capitalization(usr_str):
list_of_sentences = usr_str.split(".")
list_of_sentences.pop() #remove last element: ""
new_str = ''
for sentence in list_of_sentences:
new_str += sentence.capitalize() + "."
return new_str
print(fix_capitalization(usr_str))
For instance, if I input "hi. hello. hey." I expect it to output "Hi. Hello. Hey." but instead, it outputs "Hi. hello. hey."
An alternative would be to build a list of strings then concatenate them:
def fix_capitalization(usr_str):
list_of_sentences = usr_str.split(".")
output = []
for sentence in list_of_sentences:
new_sentence = sentence.strip().capitalize()
# If empty, don't bother
if new_sentence:
output.append(new_sentence)
# Finally, join everything
return ". ".join(output) +"."
You've entered the sentences with spaces between them. Now when you split the list the list at the '.' character the spaces are still remaining. I checked what the elements in the list were when you split it and the result was this.
'''
['hi', ' hello', ' hey', '']
'''

Need help to translate a string to pyg latin

I want to write a function that will take a string and turn the words into Pyg Latin. That means that:
If a word begins with a vowel, add "-way" to the end. Example: "ant" becomes "ant-way".
If a word begins with a consonant cluster, move that cluster to the end and add "ay" to it. Example: "pant" becomes "ant-pay".
I've searched many posts and websites but none of them do the same way or the way I want to do it. I have to test these functions in a test and I have 4 test cases for this one. One is 'fish' and it should returns 'ish-fray' the second is 'frish' and it should returns 'ish-fray' the third is 'ish' and it should return 'ish-way' and the last is 'tis but a scratch' and it should return 'is-tay ut-bay a-way atch-scray'
I've found a program that can translate it CLOSE to what it has to be but I'm not sure how to edit it so it can return the result I'm looking for.
def pyg_latin(fir_str):
pyg = 'ay'
pyg_input = fir_str
if len(pyg_input) > 0 and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
latin = []
for item in lst:
frst = item[0]
if frst in 'aeiou':
item = item + pyg
else:
item = item[1:] + frst + pyg
latin.append(item)
return ' '.join(latin)
So, this is the result my code does:
pyg_latin('fish')
#it returns
'ishfay'
What I want it to return isn't much different but I dont know how to add it in
pyg_latin('fish')
#it returns
'ish-fay'
Think about what the string should look like.
Chunk of text, followed by a hyphen, followed by the first letter (if it’s a not a vowel), followed by “ay”.
You can use python string formatting or just add the strings together:
Item[1:] + “-“ + frst + pyg
It is also worth learning how array slicing works and how strings are arrays that can be accessed through the notation. The following code appears to work for your test cases. You should refactor it and understand what each line does. Make the solution more robust but adding test scenarios like '1st' or a sentence with punctuation. You could also build a function that creates the pig latin string and returns it then refactor the code to utilize that.
def pg(w):
w = w.lower()
string = ''
if w[0] not in 'aeiou':
if w[1] not in 'aeiou':
string = w[2:] + "-" + w[:2] + "ay"
return string
else:
string = w[1:] + "-" + w[0] + "ay"
return string
else:
string = w + "-" + "way"
return string
words = ['fish', 'frish', 'ish', 'tis but a scratch']
for word in words:
# Type check the incoming object and raise an error if it is not a list or string
# This allows handling both 'fish' and 'tis but a scratch' but not 5.
if isinstance(word, str):
new_phrase = ''
if ' ' in word:
for w in word.split(' '):
new_phrase += (pg(w)) + ' '
else:
new_phrase = pg(word)
print(new_phrase)
# Raise a Type exception if the object being processed is not a string
else:
raise TypeError

If statemts, only if the subject is of a certian class

For an assignment have to turn words into the dog lantin version of them, thats not the problem though, they love to find the conditions for our code to fail, so i think they will attempt to trip us up by having different class types in the auto code. My problem is i want to apply my function to a sentence, I can do it for an indivdual word, but I dont know how to have it apply for every word in the sentece. So i have one function here
def dog_latinify_word(word):
"""Takes a word and returns the dog latin version of the word"""
first_letter = word[0]
first_letter.lower()
vowels = ('a','e','i','o','u','1','2','3','4','5',
'6','7','8','9','0')
dogify_vowel = word + 'woof'
dogify_constant = word[1:] + word[0] + "oof"
if word.startswith(vowels):
result = dogify_vowel
elif first_letter != vowels:
result = dogify_constant
return result
but i dont know how to have this function work on every item in a list, because i need to have each word be "dog latinified"
So I have another function to take the sentence that then splits it so each word is its own item in a list, but when I go to call on this function, it only works for class str, and not list. So in my rambling ways can someone point me in the direction of having this function apply into every item in a list, rather than just a string
my code for the secondary function
def dog_latinify_sentence(sentence):
"""translate a sentence into dog latin"""
str_split = sentence.split(' ')
dogify_sentence = dog_latinify_word(str_split)
return dogify_sentence
sorry for the rambling im very tired
You can fix this by just adding a for loop over the list object like this.
def dog_latinify_sentence(sentence):
"""translate a sentence into dog latin"""
str_split = sentence.split(' ')
dogify_sentence = ""
for s in str_split:
dogify_sentence += dog_latinify_word(s)
return dogify_sentence
Above code removes spaces between words. In case you want to preserve spaces,
dogify_sentence = " ".join([dog_latinify_word(s) for s in str_split])
It just gets results from dog_latinify_word() and stitch them back!

Translation from English to Pig Latin

I'm doing part of the 'PigLatin translation' program.
Here is the part I'm doing writing right now.
input_str = input("Input a word: ")
consonant_check = 0
while input_str[int(consonant_check)] != 'a' or 'e' or 'i' or 'u':
output_str = input_str[:int(consonant_check)] + input_str[0,int(consonant_check)] + 'ay'
consonant_check = int(consonant_check) + 1
else:
print(output_str)
This part is supposed to check if the word input begins with a consonant. If it does, the program could remove all consonants from the beginning of the word and append them to the end of the word. Then append "ay" to the end of the word.
By collecting information online I had some clues about how to make it happen but I think there are still something wrong with my code.
I would approach it similar to what you intended, resulting in the code below.
In short, check the first character of a string. If it's not a vowel (not in ['a','e','i','o','u']), move the character to the end of the string. Keep doing that until you hit a vowel (so 'string' becomes 'trings' then 'ringst' then 'ingstr' before breaking the loop). Once you finally hit a vowel, you leave the loop, and print the modified string + 'ay'. If the first character is a vowel, you leave the loop and print the string + 'ay'.
There's no need to set a consonant check - you're always checking the first character (0). And there's no need to have two variables - just keep modifying and replacing the original string.
word_string = input("Input a word: ")
while word_string[0] not in ['a','e','i','o','u']:
word_string = word_string[1:] + word_string[0:1]
else:
print(word_string + 'ay')
This isn't a direct answer to your question, but my solution to the pig-latin problem. When learning python, I found that looking at completed examples helped a great deal.
word = "snake"
import string
# Create a list of vowels an consonants
vowels = ['a','e','i','o','u','y']
vowels += [v.upper() for v in vowels]
consonants = [x for x in string.ascii_letters if x not in vowels]
if word[0] in consonants:
# Find the first vowel
idx = min([word.find(v) for v in vowels if word.find(v)>0])
# Split the word at this point and add 'ay'
word = word[idx:] + word[:idx] + 'ay'
print(word)
# Returns "akesnay"
I think your logic is overall a little messed up. I would suggest tackling the problem like this.
1.) Check to see if the first letter is a consonant, if not, do nothing, if so, go to step 2
2.) Find all of the consonants in the word and store them in a list
3.) If it is, remove the vowels from the word, and then append all of the consonant onto the end, followed by 'ay'.
There are infinite ways to actually implement this and I think it would be a good exercise for you to try to implement it yourself, but let me know if you need any more help.

Categories