Removing the square brackets, commas and single quote? - python

Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
when I test the function with
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
I get ['ookcoo', 'emoo', 'omesoo', 'eggsmoo'] but I want ookcoo emoo omesoo eggsmoo

Just add an asterisk before the variable name to unpack the list and feed its elements as positional arguments to print.
print(*cow_latin)

Use ' '.join(list) for concatenating the list elements into a string.
In your code:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return ' '.join([cow_latinify_word(word) for word in words])

Your function cow_latinify_sentence returns a list of strings you need to join with spaces to get your desired output:
print(" ".join(cow_latin))

Let's define our variables:
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"
Find the cow-latin:
>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'

Related

How to solve the string indices must be integers problem in a for loop for capitalizing every word in a 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)

How to convert the following code output in one line using join in python.. currently for two word input i am getting output in two lines

def cat_latin_word(text):
""" convert the string in another form
"""
constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
for word in text.split():
if word[0] in constant:
word = (str(word)[-1:] + str(word)[:4] + "eeoow")
else:
word = (str(word) + "eeoow")
print(word)
def main():
""" converts"""
text = input("Enter a sentence ")
cat_latin_word(text)
main()
A few pointers:
Converting your code to "one line" doesn't make it better.
No need to type out all consonants, use the string module and use set for O(1) lookup complexity.
Use formatted string literals (Python 3.6+) for more readable and efficient code.
No need to use str on variables which are already strings.
For a single line, you can use a list comprehension with a ternary statement and ' '.join.
Here's a working example:
from string import ascii_lowercase, ascii_uppercase
def cat_latin_word(text):
consonants = (set(ascii_lowercase) | set(ascii_uppercase)) - set('aeiouAEIOU')
print(' '.join([f'{word}eeow' if not word[0] in consonants else \
f'{word[-1:]}{word[:4]}eeoow' for word in text.split()]))
text = input("Enter a sentence ")
cat_latin_word(text)
You may use a list to put all the words or use print() in a different way.
Example:
print(word, end="\t")
where here I use the keyword argument end to set it to '\t' ( by default is '\n')
Simply edited your code to return the results as a words separated by space.
def cat_latin_word(text):
constant = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
result = []
for word in text.split():
if word[0] in constant:
word = (str(word)[-1:] + str(word)[:4] + "eeoow")
result.append(word)
else:
word = (str(word) + "eeoow")
result.append(word)
return ' '.join(result)
def main():
text = 'ankit jaiswal'
print(cat_latin_word(text))

Pig Latin In Python Conversion

def convert_pig_latin(pig):
first_letter = pig[0]
#Check if Vowel
if first_letter in 'aeiou':
pig_word = pig + 'ay'
else:
pig_word = pig[1:] + first_letter + 'ay'
print('Pig Latin:',pig_word)
So basically, this only works for 1 single word input. Let's say the user enters a sentence, it won't work which is obvious. This code is in my functions tab, and my main module of course runs it with an input sentence given. Could someone please help me out how it'll take a whole sentence instead of just one word -.- Tried using a for loop but messed it up.
Appreciate it, thanks!
You could use a list comprehension here:
def pig_latin(sentence):
return ' '.join([s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' for s in sentence.split()])
print(pig_latin("convert all the words"))
Output:
onvertcay allay hetay ordsway
You could also keep your current approach where the function converts a single word, and use map():
>>> def pig_latin_word(s):
... return s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay'
...
>>> ' '.join(map(pig_latin_word, "convert all the words".split()))
'onvertcay allay hetay ordsway'
>>>
Convert the string into a list of strings:
words = pig.split(' ')
Then you would run a for loop on the list:
for word in words:
#run your conversation code on each word
Then join the list back into a string:
pig = ' '.join(words)

how to shift a string to right and reverse it in python?

Shift word to right and then reverse it.
You should take a word shift to right and reverse it then return as follows:
>>> shift_reverse('Introduction to Computer Programming')
gnimmargorP noitcudortnI ot retupmoC
I tried using this method to find the above answer but it doesnt seem to work
Please help :(
s= "I Me You"
def shift_reverse(s):
l= s.split()
new_str= ' '.join(l[-1:] + l[:-1])
new_str = new_str[::-1]
return (new_str)
print (shift_reverse(s))
but the print i get is
[evaluate untitled-3.py]
eM I uoY
You need to reverse each of the re-ordered list:
reordered = l[-1:] + l[:-1]
new_str = ' '.join(word[::-1] for word in reordered)
You can join a generator expression that generates reversed words in the rotated split list:
>>> s = 'Introduction to Computer Programming'
>>> ' '.join(w[::-1] for w in (lambda l: l[-1:] + l[:-1])(s.split()))
'gnimmargorP noitcudortnI ot retupmoC'
Here is a step by step with the functions:
Create shift function to move last word to beginning:
def shift(sentence):
words = sentence.split()
return ' '.join([words[-1]] + words[:-1])
Create reverse function to reverse all words in a sentence (uses list comprehension):
def reverse(sentence):
return ' '.join([word[::-1] for word in sentence.split()])
Create shift_reverse to reverse all words and then shift the last on to the start:
def shift_reverse(sentence):
return shift(reverse(sentence))
Result:
shift_reverse('Introduction to Computer Programming')
Output:
'gnimmargorP noitcudortnI ot retupmoC'
In new_str = new_str[::1], you're reversing the entire string, character per character.
ghi abc def
fed cba ihg
You have to reverse each word in the list of words.
def shift_reverse(string):
words = string.split()
shifted_words = [words[-1]] + words[:-1]
return ' '.join([word[::-1] for word in shifted_words])
You can shift the string over, the reverse each item:
>>> phrase = 'Introduction to Computer Programming'
>>> new = ' '.join([word[::-1] for word in [phrase.split()[-1]]+phrase.split()[:-1]])
>>> print new
gnimmargorP noitcudortnI ot retupmoC
>>>
def shift_reverse(s):
rev = ["".join(reversed(word)) for word in s.split(" ")]
return "{} {}".format(rev.pop(), " ".join(rev))
reverse all the strings, pop the last off the list of reversed words and join the remainder.
This should work for you
s= "Introduction to Computer Programming"
def shift_reverse(s):
l= s.split()
l = [l.pop()]+ l
return ' '.join(i[::-1] for i in l)
print (shift_reverse(s))
output:
gnimmargorP noitcudortnI ot retupmoC

Python list, .replace() problems

sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for i in sentence:
if i.isalpha() == True:
if i[0] in vowels:
print(i + "way")
new = i + "way"
sentence.replace(i, new)
else:
print(i[1:] + i[0] + "ay")
new = i[1:] + i[0] + "ay"
sentence.replace(i, new)
else:
print(i)
print(sentence)
I am trying to make a piglatin sentence converter, I have been able to make the converter print the correct values for the translation, but I cannot make the program change the actual values of the list, which I need it to do so that I can print the converted text like the original, in a string format like "I like rabbits" instead of a list like:
I
like
rabbits
I would like to know how I use the replace() function to change my list inside my for loop and if statements. If there is another way that is better that would be even better.
Thank You.
sentence.replace(i, new) function returns the new string - it doesn't do replacement in-place (on the original string).
You'd want to loop through indexes to easily modify the list being iterated over (you don't change your wheels whilst driving, do you?):
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx in range(len(sentence)):
to_replace = sentence[idx]
if to_replace.isalpha() == True:
if to_replace[0] in vowels:
print(to_replace + "way")
new = i + "way"
else:
print(to_replace[1:] + to_replace[0] + "ay")
new = to_replace[1:] + to_replace[0] + "ay"
sentence[idx] = new
else:
print(to_replace)
print(sentence)
You don't really need to call replace() (which is a string method, not list). You'd assign to sentence[idx] instead.
Your list doesn't have a .replace method but, the str's in the list do.
It looks as though you are wanting to modify your list while iterating through the items.
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx, word in enumerate(sentence):
if word.isalpha() == True:
if word[0] in vowels:
print(word + "way")
new = word + "way"
else:
print(word[1:] + word[0] + "ay")
new = word[1:] + word[0] + "ay"
sentence[idx] = new
else:
print(word)
print(sentence)
The enumerate builtin is especially useful when iterating and modifying items.

Categories

Resources