I'm stuck on a really hard question for my class in which I need to create a Pig Latin converter in Python for a given string.
Basically, here are the rules.
For any word that begins with one or more consonants (y is considered a consonant):
move the consonants to the end of the word and append the string 'ay'.
For all other words, append the string 'way' to the end.
The function also must be case deal with punctuation and case sensitivity, it is suggested that we create a separate function to find the initial vowel of any word and use it in the main function, which I kinda did, however, I'm having trouble implementing the Case and punctuation into my main formula and what to do if a word has no vowels (since "y" doesn't count as a vowel in our case, the word "my" doesn't have a vowel.
Here's my code so far.
def vowelfinder(astring):
vowels = ["A","E","I","O","U","a","e","i","o","u"]
alist = astring.split()
for i in alist:
for j in range(len(i)):
if i[j] in vowels:
print(j)
break
def igpay(astring):
vowelfinder(astring)
for i in alist
Any advice is helpful
# For any word that begins with one or more consonants (y is considered a consonant):
if "aeiouAEIOU".find(astring[0]) == -1:
# move the consonants to the end of the word and append the string 'ay'.
return astring[1:] + astring[0] + "ay"
# For all other words,
else:
# append the string 'way' to the end.
return astring + "way"
This is for a word. Splitting into words should be easy enough.
EDIT: brainfart.
Related
So I’m trying to write a Python 3 function for a challenge that takes in a string, removes the vowels and returns it without the vowels. I wrote the below code but it seems to only take out the vowels partially while leaving some untouched.
def remove_vowels(string):
vowels = ['a','e','i','o','u']
newstring = ""
for letter in string:
if letter in vowels:
newstring = string.replace(letter,””)
else:
pass
return newstring
Your original python code with the following input
print(remove_vowels("The quick brown fox jumps over the lazy dog"))
returns "The quick brwn fx jumps ver the lazy dg"
The reason this only removes the "o" vowel is because your iterating through each vowel and updating your new string to the passed string minus the current vowel your on. So for example the first time through your for loop your "newstring" variable will be:
The quick brown fox jumps over the lzy dog
Then the next iteration your "newstring" variable will be set to
Th quick brown fox jumps ovr th lazy dog
And so on and so on. The reason my example only removes the o's is because there is no U to replace so the string replace method is never called leaving the "newstring" variables without o's.
To fix this you would just remove newstring completely and update the original string as this is it's own variable and this would technically work as is.
Although this can be compressed and refactored for better performance quite easily as you don't actually need to iterate through your string at all (nor do you need any type of new string as the passed string is it's own variable you are able to update) as pythons "String.replace" will replace ALL occurrences of the supplied substring and return the resulting string (if you don't supply a max amount of occurrences).
The following code below works
def remove_vowels(string):
vowels = 'aeiou'
for vowel in vowels: string = string.replace(vowel,'')
return string
print(remove_vowels("The quick brown fox jumps over the lazy dog"))
and returns "Th qck brwn fx jmps vr th lzy dg"
That's because you're setting newstring to a different string output on every iteration of the loop newstring = string.replace("")
You need to set newstring to the replaced string, and then run the next iteration of replace on newstring. Like this:
def remove_vowels(string):
vowels = ['a','e','i','o','u']
newstring = string
for letter in newstring:
if letter in vowels:
newstring = newstring.replace(letter , "")
return newstring
string = "stack overflow"
print("Original string = ", string)
print("String with vowels removed = ", remove_vowels(string))
Output:
Original string = stack overflow
String with vowels removed = stck vrflw
An alternative, short solution with a list comprehension:
def remove_vowels(string):
not_vowels = [letter for letter in string if letter not in 'aeiou']
return ''.join(not_vowels)
Make the following modifications to your code and it should work like a charm :)
def remove_vowels(string):
vowels = 'aeiou'
for letter in string:
if letter in vowels:
string = string.replace(letter," ")
else:
pass
return string
You are replacing a character in original string each time, but the original string never changes with current logic (except in the last loop).
try this inside IF condition
newstring = newstring.replace(letter,"")
(also initialize newstring = string before for loop)
Your code has several defects:
You are updating new_string with string, which does not change, and that results in only the last vowel in the list is deleted.
You do not need else: pass, it's ok with only the if clause. The else: pass is redundant.
You are cycling through the letters in string, which is not the fastest way to do things, also, it will create all kinds of weird errors if your code is changing string. You can knock outfor i in new_string:if i in vowels with for i in vowels
The vowels does not have to be a list if you are only iterating over it.Try a tuple or a str for better efficiency.
The overall fix:
def remove_vowels(string):
vowels = ('a','e','i','o','u')
newstring = string
for letter in vowels:
newstring = newstring.replace(letter,””)
return newstring
or:
def remove_vowels(string):
vowels = ('a','e','i','o','u')
for letter in vowels:
string = string.replace(letter,””)
return string
I hope everyone is safe.
I am trying to go over a string and capitalize every first letter of the string.
I know I can use .title() but
a) I want to figure out how to use capitalize or something else in this case - basics, and
b) The strings in the tests, have some words with (') which makes .title() confused and capitalize the letter after the (').
def to_jaden_case(string):
appended_string = ''
word = len(string.split())
for word in string:
new_word = string[word].capitalize()
appended_string +=str(new_word)
return appended_string
The problem is the interpreter gives me "TypeError: string indices must be integers" even tho I have an integer input in 'word'. Any help?
thanks!
You are doing some strange things in the code.
First, you split the string just to count the number of words, but don't store it to manipulate the words after that.
Second, when iterating a string with a for in, what you get are the characters of the string, not the words.
I have made a small snippet to help you do what you desire:
def first_letter_of_word_upper(string, exclusions=["a", "the"]):
words = string.split()
for i, w in enumerate(words):
if w not in exclusions:
words[i] = w[0].upper() + w[1:]
return " ".join(words)
test = first_letter_of_word_upper("miguel angelo santos bicudo")
test2 = first_letter_of_word_upper("doing a bunch of things", ["a", "of"])
print(test)
print(test2)
Notes:
I assigned the value of the string splitting to a variable to use it in the loop
As a bonus, I included a list to allow you exclude words that you don't want to capitalize.
I use the original same array of split words to build the result... and then join based on that array. This a way to do it efficiently.
Also, I show some useful Python tricks... first is enumerate(iterable) that returns tuples (i, j) where i is the positional index, and j is the value at that position. Second, I use w[1:] to get a substring of the current word that starts at character index 1 and goes all the way to the end of the string. Ah, and also the usage of optional parameters in the list of arguments of the function... really useful things to learn! If you didn't know them already. =)
You have a logical error in your code:
You have used word = len(string.split()) which is of no use ,Also there is an issue in the for loop logic.
Try this below :
def to_jaden_case(string):
appended_string = ''
word_list = string.split()
for i in range(len(word_list)):
new_word = word_list[i].capitalize()
appended_string += str(new_word) + " "
return appended_string
from re import findall
def capitalize_words(string):
words = findall(r'\w+[\']*\w+', string)
for word in words:
string = string.replace(word, word.capitalize())
return string
This just grabs all the words in the string, then replaces the words in the original string, the characters inside the [ ] will be included in the word aswell
You are using string index to access another string word is a string you are accessing word using string[word] this causing the error.
def to_jaden_case(string):
appended_string = ''
for word in string.split():
new_word = word.capitalize()
appended_string += new_word
return appended_string
Simple solution using map()
def to_jaden_case(string):
return ' '.join(map(str.capitalize, string.split()))
In for word in string: word will iterate over the characters in string. What you want to do is something like this:
def to_jaden_case(string):
appended_string = ''
splitted_string = string.split()
for word in splitted_string:
new_word = word.capitalize()
appended_string += new_word
return appended_string
The output for to_jaden_case("abc def ghi") is now "AbcDefGhi", this is CammelCase. I suppose you actually want this: "Abc Def Ghi". To achieve that, you must do:
def to_jaden_case(string):
appended_string = ''
splitted_string = string.split()
for word in splitted_string:
new_word = word.capitalize()
appended_string += new_word + " "
return appended_string[:-1] # removes the last space.
Look, in your code word is a character of string, it is not index, therefore you can't use string[word], you can correct this problem by modifying your loop or using word instead of string[word]
So your rectified code will be:
def to_jaden_case(string):
appended_string = ''
for word in range(len(string)):
new_word = string[word].capitalize()
appended_string +=str(new_word)
return appended_string
Here I Changed The Third Line for word in string with for word in len(string), the counterpart give you index of each character and you can use them!
Also I removed the split line, because it's unnecessary and you can do it on for loop like len(string)
I am a beginner in Python, and I want my code to move the first one or two consonants to the end of the word and add -ay. I have gotten my code to do this but it doesn't work for sentences. I need help with the list. Also, the returned, translated sentence needs to start with an uppercase letter and end with a period, just like the input sentence but I have no clue where to start with this! Here is my code so far:
pyg = 'ay'
original = raw_input('Enter a sentence:')
word = original.lower()
word_list = word.split
count = 0
for word in word_list:
if word[1] == "a" or word[1] == "e" or word[1] == "i" or word[1] == "u" or
word[1] == "o" or word[1] == "y":
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word
else:
if word[1] != "a" or word[1] != "e" or word[1] != "i" or word[1] != "u" or
word[1] != "o" or word[1] != "y":
first = word[0]
second = word[1]
second_word = word + first + second + pyg
second_word = second_word[2:len(second_word)]
print second_word
I have tried creating the code using .format() , being beginner myself , I hope you find this code easy & helpful.
def pig_latin(text):
say = ""
words = text.split()
for word in words:
say += "{}{}{} ".format(word[1:], word[0], "ay")
return say
print(pig_latin("hello how are you"))
ellohay owhay reaay ouyay
This is a slightly generalized version of what you say you want. The difference is that the code below doesn't look at the first one or two letters: it shifts all initial consonants to the end, so that string becomes ingstray. Your problem statement says that should be ringstay, but that doesn't accord with the Pig Latin I learnt as a child. I've done this partly because I think your specification is incomplete, and partly because it makes the code simpler, and that makes it easier to understand. You can always amend the code if ringstay is really what you want. (Hint: put a counter in the while loop.) There is also a bug in this code, though you would be unlikely to find it: if an input word contains no vowels at all, for example cwm (a kind of Welsh fiddle) then the while loop will never terminate. (Hint: same solution.)
I haven't added the refinement, also dimly remembered from my childhood, that an original word that begins with a vowel gets the suffix way not ay, so I am good comes out as Iway amway oodgay not Iay amay oodgay.
The Pythonic way to do a membership test is to use in, not a long string of if x == 'a' or x == 'b' or x == 'c' tests.
Providing an initial capital and a final fullstop requires you to split the problem into two: (1) transform the words, and (2) punctuate the sentence. You can't do that if you print the transformed words out as you go along. So the code below assembles the words into a result list and then strings the list of words into a final sentence for punctuation.
pyg = 'ay'
original = raw_input('Enter a sentence:')
word_list = original.lower().split()
result = []
for word in word_list:
while word[0] not in "aeiouy":
word = word[1:] + word[0]
word += pyg
result.append(word)
final_sentence = " ".join(result)
print final_sentence[0].upper() + final_sentence[1:] + "."
Personally I consider it not good style to store a sentence in a variable called word, especially if the code actually stores a word in that same variable at a later point. So I've amended that too.
Edit since it appears my hint wasn't explicit enough:
To limit the number of consonants that get shifted to the end, you need to count them:
for word in word_list:
consonants = 0
while word[0] not in "aeiouy" and consonants < 2:
word = word[1:] + word[0]
consonants += 1
word += pyg
result.append(word)
To make sure the program isn't put into an infinite loop by a word with no consonants:
while word[0] not in "aeiouy" and consonants < len(word):
THe rules for the pig latin sentences are:
1.for words beginning with consonants, all letters before the first vowel are moved to the end of the word, and is further appended by 'ay'
2.for words that begin with vowels, the word is appended by 'hay'
3.for words that do not contain a vowel, the first letter is moved to the end of the word and is appended with 'way'
4. all non characters (i.e., numbers, symbols) are ignored
The main part of the code executes an infinite loop that takes a string input from the user, invokes the pigLatin function and prints the result returned. The pigLatin function receives a list of words as its input and converts them to pig latin using the rules above. The main part exits when the user input "Quit this program" as the input sentence for conversion. Verify your program for all cases (including invalid inputs) and save your program.
I find it very difficult to solve rule 3. As I test the code, the out put isn't correct...
I struggle it for the whole night and couldn't sleep....Please help
Here is my code:
enter code here
sentence=input('input:')
VOWELS=['a','e','i','o','u']
CONSONANTS=['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
def pigLatin():
t=-1
for word in newsentence:
if word[0] in CONSONANTS:
if 'a'and'e'and'i'and'o'and'u' not in word[1:]:
print(word[1:]+word[0]+'way',end=' ')
for u in word:
t +=1
if u in VOWELS:
print (word[t:]+word[0:t]+'ay',end=' ')
break
elif word[0] in VOWELS:
print (word[0:]+'hay',end=' ')
else:
print (word[0:])
while sentence!=('Quit the program'):
newsentence=sentence.split()
pigLatin()
sentence=input('input:')
As Willem Van Onsem said, this line doesn't do what you think:
if 'a'and'e'and'i'and'o'and'u' not in word[1:]:
You should try experimenting with the interpreter.
'a' and 'e' not in "bar"
# returns True
This is happening because and is a logical operator which looks at what comes before and after it. It is doing this:
'a' and ('e' not in "bar")
which evaluates to
'a' and True
which evaluates to True, because non-empty strings get assigned the boolean True.
Here is something that will work. It uses the all function, which only returns True if all of its elements are true, and a feature of Python called comprehension which allows you to do tidy loops:
vowels = "aeiou"
all(char not in vowels for char in word)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So the question reads:
Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string "StopAndSmellTheRoses." would be converted to " Stop and smell the roses."
I am so confused this my code so far.
def main():
#User enters a sentence
my_string=input('enter a sentence: ')
print(my_string.capitalize())
main()
You can loop through the string and add a character each time to a result:
my_string = "StopAndSmellTheRoses"
i = 0
result = ""
for c in my_string:
if c.isupper() and i > 0:
result += " "
result += c.lower()
else:
result += c
i += 1
print result
We'll use c for each character as we walk through the string and we'll use i to keep track of the position in the string.
There are two possibilities: it's either an uppercase character (excluding the first one) or it's not.
In the first case we'll add a space and that character as lowercase to the result. This ensures a space is inserted before each uppercase character further in the sentence.
In the second case it's a lowercase character or the uppercase character at the beginning of the sentence. We don't have to do anything with these and we'll add it right away.
Lastly we add one to i whenever we're done with a character (i += 1) as this means we correctly know where we are in the sentence.
Welcome to SO!
One way to do this is to loop through your string, checking the chars one by one:
#You've learned how to iterate through something, right?
i = 0 #a counter
for c in my_string: #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
i += 1
Edit added a double-check to see if it's the first letter of the sentence or not. Updated demo.
As an alternative to using a counter, you can also use the built-in function enumerate, which returns a tuple of index and values.
for i,c in enumerate(my_string): #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+c.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
Demo
>>> my_string = 'ImCool'
>>> new_string = ''
>>> i = 0 #a counter
>>> for c in my_string: #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
i += 1
>>> new_string
'Im cool'
Hope this helps!
You'll need a bit of regex.
import re
split = re.findall(r'[A-Z][a-z\.]+', 'HelloThisIsMyString.')
You'll also need to join those together (inserting spaces)
' '.join(...)
and handle case conversions
' '.join(word.lower() for word in split)
(and as you already did, capitalize the first word)
' '.join(word.lower() for word in split).capitalize()
It appears that you are a little confused and this is to be expected if you are new to Python. I'm assuming you take input from the user as opposed to input for a function. Either way I would create a simple function that you could insert the users input into. The function below will accomplish what the problem asks.
def sentenceSplitter(sentence):
result = ""
for i, x in enumerate(sentence): #i is character index, x is the element
if i == 0:
result = result + x
elif x.isupper() == False: #if element is not uppercase, add it to the result
result = result + x
else: # Otherwise, add a space and lowercase the next letter
result = result + " " +x.lower()
return(result)
To reiterate, if you are looking to print out the sentence you would write this after the function:
def main():
#User enters a sentence
my_string=input('enter a sentence: ')
print(sentenceSplitter(my_string))
main()
If you are still confused feel free to ask any further questions.