Python add string before every vowel - python

I am writing a python code that takes a single imputed line of text and adds the string "tak" before every vowel (y only counting as a vowel if it doesn't begin a word) for example "I like sleep" would come out to "takI ltakitake sltaketakep". I am only just beginning learning to code and as such do not know too many complex functions yet. Below is the code I have thus far, which isn't working at all.
text = raw_input("enter the text to be translated")
textSplit = text.split()
count = 0
print len(textSplit)
Vowels = ["a","e","i","o","u"]
while count <= len(text):
for i in textSplit:
for i in Vowels:
count += 1
However, I have not been able to figure out how I can slice the string, add "tak" and concatenate it.
Thank you.
edit: can it be done without using the text.replace module?

You can use a regex:
>>> re.sub(r'(?i)([aeiou])', r'tak\1', "I like sleep")
'takI ltakiktake sltaketakep'
You can also use str.replace by looping over the string once for each vowel. Don't forget that strings are immutable in Python so you have to create a new string each time:
>>> s="I like sleep"
>>> for v in 'aeiouAEIOU':
... s=s.replace(v, 'tak'+v)
...
>>> s
'takI ltakiktake sltaketakep'
In this case, the string s is either the same as before if the vowel is not found or each vowel is replaced by the string tak concatenated to the vowel. A new string is created in either case each time through the loop and assigned to s.

You could use re.sub:
re.sub(r'([aeiou])', r'(exampleReplace)\1', text)
Example:
text = 'Text'
print(re.sub(r'([aeiou])', r'(exampleReplace)\1', text))
>> T(exampleReplace)ext

If you need to ignore any leading 'y's, you'll have to finesse it just a bit:
text = raw_input("enter the text to be translated")
temp1 = temp2 = text[1:] if text[0] in ['y', 'Y'] else text
for vowel in ['a', 'e', 'i', 'o', 'u', 'y']:
temp2 = temp2.replace(vowel, 'tak{}'.format(vowel))
temp2 = temp2.replace(vowel.upper(), 'tak{}'.format(vowel.upper()))
text = text.replace(temp1, temp2)
print text
For an input of 'I like sleep', this gives:
takI ltakiktake sltaketakep
'yellow':
ytakelltakow
'turkey':
ttakurktaketaky
If, for some reason, you really didn't want to use str.replace, you could do it like this:
text = raw_input("enter the text to be translated")
temp2 = text[1:] if text[0] in ['y', 'Y'] else text
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
temp2 = ''.join(['tak{}'.format(letter) if letter.lower() in vowels else letter for letter in temp2])
if text[0] in ['y', 'Y']:
text = text[0] + temp2
else:
text = temp2
print text

Use list() instead of split(). I have also used enumerate to get the index and value simultaneously.
Modified code:
text = "I like banana"
textSplit = list(text)
Vowels = ["a","e","i","o","u"]
for index,letter in enumerate(textSplit):
if letter.lower() in Vowels:
textSplit[index] = "tak" + letter
print "".join(textSplit)
Output:
takI ltakiktake btakantakantaka

The following would work:
text = 'I like sleep'
vowels = set("aeiou")
modified_text = ''.join(['tak'+letter if letter.lower() in vowels else letter for letter in text])
print(modified_text)
Output
takI ltakiktake sltaketakep
(note: I think you are missing a k in your sample output)

Related

How to reverse vowels in string and return it

I am Trying to make a program in Python to reverse the vowels in a string and return the string like this:
vow = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
vowin = []
place = []
def string(string):
for ch in string:
if ch in vow:
vowin.append(ch)
else:
continue
for ch in string:
if ch in vow:
index1 = string.index(ch)
place.append(index1)
else:
continue
place.reverse()
str = list(string)
for ch in range(len(place)):
str[place[ch]] = vowin[ch]
new = ''.join(str)
return new
print(string('Queen'))
When I try to run a word with a double vowel like queen it makes all other vowels into e too like the code above.
Output: Qeeen
but if I input hello the output is holle like it should.
Anyone know what the problem is?
No indexing required if vowin is used as a LIFO (last in, first out) stack. First pass, fill with vowels in order. Second pass, each vowel is replaced from vowin via .pop() which removes the last value.
vow = 'aeiouAEIOU'
def string(s):
vowin = [] # make sure to reset each call to string()
place = []
for ch in s:
if ch in vow:
vowin.append(ch) # store vowels in order found
for ch in s:
if ch in vow: # if vowel
place.append(vowin.pop()) # replace in reverse order
else:
place.append(ch) # else copy as is
new = ''.join(place)
return new
print(string('Queen'))
print(string('abcdefghijklmnopqrstuvwxyz'))
print(string('bookkeeping'))
Output:
Qeeun
ubcdofghijklmnepqrstavwxyz
biekkeopong
this code uses a list comprehension to extract the vowels from the input string.
the resampling of the final string is done by using a ternary conditional.
inp = input()
vow = 'aeiouAEIOU'
vow_lst = [char for char in inp if char in vow]
res = ''
for char in inp:
res += vow_lst.pop() if char in vow else char
print(res)

Get first character of each line from string with multiple lines in Python

I have below string with multiple line:
data = """
Come to the
River
Of my
Soulful
Sentiments
Meandering silently
Yearning for release.
Hasten
Earnestly
As my love flows by
Rushing through the flood-gates
To your heart.
"""
I want to get a string including the first character of each line in Python.
It should return the result: 'Crossmyheart'
Try
data = """
Come to the
River
Of my
Soulful
Sentiments
Meandering silently
Yearning for release.
Hasten
Earnestly
As my love flows by
Rushing through the flood-gates
To your heart.
"""
# Get each line into a list by splitting data on every newline
# ['', 'Come to the', 'River', 'Of my', ... 'To your heart.', '']
data_list = data.split("\n")
# Get a list of the first letter of every list element
# use only those elements with length > 0
# ['C', 'R', 'O', 'S', 'S', 'M', 'Y', 'H', 'E', 'A', 'R', 'T']
letters_list = [x[0] for x in data_list if len(x)>0]
# Join it to make one word
# 'CROSSMYHEART'
my_word = ''.join(letters_list)
# Capitalise only the first letter
my_word = my_word.capitalize()
# Print out the answer.
# 'Crossmyheart'
print(my_word)
Here's a quick solution I could find
data = ["Come to the", "River", "Of my", "Soulful", "Sentiments", "Meandering silently", "Yearning for release", "Hasten", "Earnestly", "As my love flows by", "Rushing through the flood-gates", "To your heart"]
newString = ""
for word in data:
letter = word[0]
newString = newString + letter
print(newString[-1], end=" ")
You first need to split your data into a list, then select lines that are not empty, append the first character of the string to a list and finally join the list to form a string.
It can be achieved in a single python line
x = ''.join([i[0] for i in data.splitlines() if len(i) > 0])
I think you could leverage the built in regex lib found in python as the first letter of each line contains a capital letter.
>>> import re
>>> def get_first_letter(data):
... # Extracts the first capital letter in each line
... first_letter_each_line = re.findall(r'[A-Z]', data)
... # Concatenates it
... concat = ''.join(first_letter_each_line)
... # Formats string
... return concat.capitalize()
>>> get_first_letter(data)
'Crossmyheart'
data = """
Come to the
River
Of my
Soulful
Sentiments
Meandering silently
Yearning for release.
Hasten
Earnestly
As my love flows by
Rushing through the flood-gates
To your heart.
"""
text = data[1];
i = 1
while i < len(data):
if i+1 == len(data):
break;
if data[i] == '\n':
text = text + data[i+1].lower()
i = i + 1
print(text)
First, I get the first character of string which easiest to find and already in capital letter.
For other character, I just used loop to checked for the new line '\n' character to get the next character after '\n' (it's the first character of line) then lower it and the concat them together. The loop will break if the next character is last character.
len() is function for find the length of string.
lower() is function for lower character/string.
Hope this might can help you ^^

How did I go off-by-one when prepending to a string in a loop?

I am trying to write a program to take a string; find and remove vowel in string, change capital letter to small letter and added "." before each letter. Here's the code:
input_string = "aBAcAba"
vowel = ["a","e","i","o","u"]
list = list(input_string.lower())
for letter in list:
if letter in vowel:
list.remove(letter)
result = ".".join(list)
print (result)
When I run this, I get:
b.c.b
But the desired result is:
.b.c.b
Why isn't . added before the first letter, and how can I fix it?
Instead of removing in place, use a list comprehension to create a new list:
input_string = "aBAcAba"
vowel = {"a","e","i","o","u"}
new_string = ''.join(["."+i.lower() for i in input_string if i.lower() not in vowel])
Output:
'.b.c.b'
Also, changing vowel from a list to a set improves the overall lookup time.
more simply
input_string = "aBAcAba"
vowel = ["a","e","i","o","u"]
list = list(input_string.lower())
for letter in list:
if letter in vowel:
list.remove(letter)
result = "."+".".join(list)
print (result)
result = ".".join(list)
will not add "." before each letter, but will result like you are getting.
if you want "." in starting also you can add extra "."
result="."+".".join(list)
If you just neeed to print it, you can add the '.' on the fly when printing it like this:
print ('', *L, sep=".") # L being the list of remaining non-vowels
This will not create a string though as print() does not return the printed string. The other answers cover how to get the string already. I would still go for a list comprehension to create the partial list:
input_string = "aBAcAba"
vowel = ["a","e","i","o","u"]
L = [c.lower() for c in input_string if c not in vowel]
print ('', *L, sep=".") # *L unpacks it to: print('','b','c','b', sep =".") for your data
The *L will unpack the list, the '' before will add an empty string before it. By declaring a sep="." print will seperate each thing it prints by a '.'
Output:
.b.c.b
inp = 'aBAcAba'
vowels = ['a', 'e', 'i', 'o', 'u']
'.'+'.'.join([c for c in inp.lower() if c not in vowels])
Basically the last line does the trick, it converts input to lower case, check character by character if it's a vowel, finally joins the list to output a string. additional '.' is added at the beginning of the string.
You can also use regular expressions to do that.
Code:
import re
input_string = "aBAcAba"
consonants = re.sub(r'[aeoiu]', '', input_string.lower())
result = f".{'.'.join(consonants)}"
I formatted the result using a Python 3.6+ feature called Literal String Interpolation. I encourage you to find out more about it.
Output:
>>> result
'.b.c.b.'
r'[aeoiuy]' is a pattern that matches one of the vowels within the square brackets.
You can read more about regular expressions here and use this site to test if they match the string.

Print only vowels in a string

I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)
For now I've got this ;
sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
Something like this?
sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
The two answers are good if you want to print all the occurrences of the vowels in the sentence -- so "Hello World" would print 'o' twice, etc.
If you only care about distinct vowels, you can instead loop over the vowels. In a sense, you're flipping the code suggested by the other answers:
sentence = input('Enter your sentence: ')
for vowel in 'aeiou':
if vowel in sentence:
print(vowel)
So, "Hey there, everything alright?" would print
a e i
As opposed to:
e e e e e i a i
And the same idea, but following Jim's method of unpacking a list comprehension to print:
print(*[v for v in 'aeiou' if v in sentence])
Supply provide an a list comprehension to print and unpack it:
>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i
This makes a list of all vowels and supplies it as positional arguments to the print call by unpacking *.
If you need distinct vowels, just supply a set comprehension:
print(*{i for i in s if i in 'aeiou'}) # prints i e a
If you need to add the else clause that prints, pre-construct the list and act on it according to if it's empty or not:
r = [i for i in s if i in 'aeiou']
if r:
print(*r)
else:
print("empty")
You could always use RegEx:
import re
sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())
if len(vowels) == 0:
for i in vowels:
print(i)
else:
print("Empty")
You can always do this:
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
characters_input = input('Type a sentence: ')
input_list = list(characters_input)
vowels_list = []
for x in input_list:
if x.lower() in vowels:
vowels_list.append(x)
vowels_string = ''.join(vowels_list)
print(vowels_string)
(I am also a beginner btw)

Displaying if there are redundant characters in a string with a list

I am wondering how you would display if there are redundant characters in a string with a list. Let me explain better. Say you have a list with "_" symbols representing a blank space:
word = ["_","_","_","_"]
Now say you have a string:
string = "door"
Let's say you want the user to guess what the word is by inputting characters Hangman-style. If their guess is right, you want that character to be in the "word" array in the same spot it is in the string, so if they guess "d", the "word" list would look like this:
word = ["d","_""_""_"]
It would print out too look like "d _ _ _". I have no problems up to this point, however when displaying redundant characters I have a problem. For example, if the user guesses "o", I can't seem to display both "o"s in "door" with the array, it always looks like this:
word = ["_", "o", "_", "_"]
I want it to look like this:
word = ["_", "o", "o", "_"]
Now please note that this question is very similar to my last one, except that that one didn't explain how to display them in a list. I also am unsure if this has been asked before, I have not found any similar questions but there still may be some. I'm just so confused I don't know what else to do! Thank you for your time. If I've broken a stackoverflow commandment by asking this, I apologize.
You need to loop over the word each time:
ans = 'door'
word = ['_' for _ in ans]
while '_' in word:
guess = raw_input('Guess a char')
for i, c in enumerate(ans):
if guess.lower() == c.lower():
word[i] = c
print word
To avoid case problems, use str.lower on both input and c.
Output:
Guess a char
d
['d', '_', '_', '_']
Guess a char
o
['d', 'o', 'o', '_']
Guess a char
r
['d', 'o', 'o', 'r']
Process finished with exit code 0
What is the way you are currently modifying the word? To make sure that every character will show up you can iterate through string: if the letter at index i in string is equal to the guess, set word[i] = guess. This ensures all letters will be caught.
It will be nice to see what code you have so far to be able to point you to the right direction, but have a look at this:
def check_guess(word, guessed_character, guess_list):
if guessed_character in word:
for index, character in enumerate(word):
if guessed_character == character:
guess_list[index] = character
return guess_list
WORD = 'door'
guess_list = ['_'] * len(WORD)
while '_' in guess_list:
guessed_character = raw_input()
print '{}'.format(check_guess(WORD, guessed_character, guess_list))
Because I wanted to see if I could get this to be a one liner:
string = 'door'
guesses = ['o'] # fill this in as you get guesses
word = [i in guesses and i or '_' for i in string]
word = 'door'
blanks = ['_' for x in word] # easy way to generate blanks from word
guess = 'o'
[guess if x == guess else '_' for x in word] #=> ['_','o','o','_']

Categories