Search list in string characters - python

I have to search if a word doesn't have a vowel, and then put them in another list.
I can't make it work, and I don't understand why.
for i in range(len(Cadena)):
if all Vocales[] not in Cadena:
Lista.append(Cadena[i])

Try this.
word = 'apple'
vowels = ['a','e','i','o','u','A','E','I','O','U']
for letter in word:
if letter in vowels:
#this word has a vowel, do something
else:
# this word doesn't have a vowel.

I'm not 100% sure what your variables mean, but your problem is simple.
Here is the solution:
# array with words that you to sort into two groups
words = ["abc", "def", " ggg"]
vowels = ["a", "e", " i", "o", " u"] # possibly include "y"
numVowels = len(vowels)
withVowels = [] # words with vowels
withoutVowels = [] # words without vowels
# categorize words
for w in words:
for i, v in enumerate(vowels):
if v in w:
withVowels.append(w)
elif i == (numVowels -1):
withoutVowels.append(w)
At the end of this for loop, the withVowels will contain ["abc", "def"] and withoutVowels will contain [" ggg"]

import re
def vocales(text):
#with regular expression.
print re.findall("[aeiouÁÉÍÓÚ]", text.lower(), re.IGNORECASE)
#or verifying letter by letter
print [e for e in text if e in "aeiouÁÉÍÓÚ"]
#Shows the characters that are not vowels
print [e for e in text if e not in "aeiouÁÉÍÓÚ"]
#Returns false if it has vowels
return not len([e for e in text if e in "aeiouÁÉÍÓÚ"])
vocales("Hola mundo. Hello world")
Output:
['o', 'a', 'u', 'o', 'e', 'o', 'o']
['o', 'a', 'u', 'o', 'e', 'o', 'o']
['H', 'l', ' ', 'm', 'n', 'd', '.', ' ', 'H', 'l', 'l', ' ', 'w', 'r', 'l', 'd']
False

You can set up a string with all your vowels, then you can use list comprehension to check your words against this string
vow = 'aeiou'
words = ['apple', 'banana', 'vsh', 'stmpd']
w_vowels = [i for i in words if any(k in vow for k in i)]
wo_vowels = [i for i in words if not any(k in vow for k in i)]
print(w_vowels) # => ['apple', 'banana']
print(wo_vowels) # => ['vsh', 'stmpd']
Expanded Loops without any:
w_vowels = []
for i in words:
for k in i:
if k in vow:
w_vowels.append(i)
break
wo_vowels = []
for i in words:
for k in i:
if k in vow:
break
else:
wo_vowels.append(i)

Related

Python: How to check if element of string is in a string and print the not included string elements?

I want to check each list element of c in alphabet and print the letters of the alphabet, which are not in a list element of c.
For example, shall the first list element of c "aa" print all letters of alphabet in a string excluding the letter a.
alphabet = "abcdefghijklmnopqrstuvwxyz"
c = ['aa', 'bb', 'zz']
for x in c:
if x in alphabet:
print(alphabet)
else:
print('not an element of alphabet')
Something like that:
alphabet = "abcdefghijklmnopqrstuvwxyz"
cases = ['aa', 'bb', 'zz']
for case in cases:
missing_letters = []
for letter in alphabet:
if letter not in case:
missing_letters.append(letter)
print(f"Case {case} misses following alphabeth letters {missing_letters}")
Output:
Case aa misses following alphabeth letters ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
If you are sure that the elements in c are all in the format of 'xx' like in your sample, then the following is a solution:
alphabet = "abcdefghijklmnopqrstuvwxyz"
c = ['ad', 'bb', 'zz','ad', 'bt', 'uz']
for x in c:
new_alph = alphabet
for char in x:
new_alph = new_alph.replace(char,'')
if new_alph == alphabet:
print('not an element of alphabet')
else:
print(new_alph)
Output:
bcefghijklmnopqrstuvwxyz
acdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcefghijklmnopqrstuvwxyz
acdefghijklmnopqrsuvwxyz
abcdefghijklmnopqrstvwxy
Another way is to use translate to make the code more compact:
alphabet = "abcdefghijklmnopqrstuvwxyz"
c = ['ad', 'bb', 'zz','ad', 'bt', 'uz']
for x in c:
new_alph = alphabet.translate({ord(char): '' for char in x})
if new_alph == alphabet:
print('not an element of alphabet')
else:
print(new_alph)
Output:
bcefghijklmnopqrstuvwxyz
acdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
bcefghijklmnopqrstuvwxyz
acdefghijklmnopqrsuvwxyz
abcdefghijklmnopqrstvwxy
As long as the strings in c are only 2 chars this will work
alphabet = "abcdefghijklmnopqrstuvwxyz"
c = ['aa', 'bb', 'zz']
for x in c:
if x[0] in alphabet or x[1] in alphabet:
alphabet.replace(x[0], '').replace(x[1], '')
else:
print('not an element of alphabet')

Append dot before each letters

I want to add a point before each letter.
Unfortunately, the point is after each letter. How to insert the point before each letter?
myText = str(input())
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ''
for letter in myText:
if letter not in vowels:
result = result + letter
for i in result:
result = result + '.'
break
print(result.lower())
A shorter and faster solution relying on the power of regular expressions:
import re
my_text = "sample"
re.sub(r"[aeiou]*([^aeiou])[aeiou]*", r".\1", my_text.lower())
This reads: “delete vowels, and prefix each remaining letter with a dot”.
Removing all vowels and append "." before each letter.
myText = "sample"
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ''
for letter in myText:
if letter not in vowels:
result = result + '.' + letter
print(result.lower())
# .s.m.p.l
Fian's answer is probably the best one. Here's my attempt:
text = 'audfijsdfmsomlasn'
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
result = ''
for letter in text:
if letter in vowels:
result += '.'
result += letter
print(result)
Yet another way:
import re
myText = "sample"
result = '.' + '.'.join(list(re.sub('[aeiou]', "", myText, flags=re.I)))
print(result)
Explanation:
re.sub removes the not required letters (case insensitive = re.I)
list makes the string an array of characters
join places a dot in between
'.' + adds the missing dot in front of the first character
string = input()
vowels = ['a', 'A', 'i', 'I', 'o', 'O', 'u', 'U', 'e', 'E']
translation = string.maketrans({i: '' for i in vowels})
string = string.translate(translation)
result = ''
for letter in string:
result = result + '.' + letter
print(result.lower())

my code to remove vowels from a string is acting weird

So I wrote this code to remove the vowels from any string given.
it should work fine. And it actually does. Just not for all strings
which is weird why it would work for some strings and not for others
here's the code:
vowels = ["a", "e", "i", "o", "u"]
def anti_vowel(text):
text1 = list(text)
print text1
for i in text1:
if i.lower() in vowels:
text1.remove(i)
text2 = "".join(text1)
return text2
and here are the tests that I placed:
print anti_vowel("my name is Omar")
print anti_vowel("Hey look Words!")
print anti_vowel("Hey look more Words to look for!")
I tried placing print statements in the middle of the code to test it and I found something weird.
the for loop iterates about 3 or 4 times to remove one vowel.
I can't seem to know why
This weird case happens when 2 vowels are right next to each other. Basically, you are looping for each letter in the word, but when you remove the letter (if it is a vowel), then you shorten the length of the word, and therefore the next letter will have skipped over the real next letter. This is a problem when the letter being skipped is a vowel, but not when it is a consonant.
So how do we solve this? Well, instead of modifying the thing we're looping over, we will make a new string and modify it. So:
text2 = ""
for letter in text1:
if letter not in vowels:
text2 += letter
return text2
This can also be achieved with list comprehension:
return "".join ([letter for letter in text1 if letter not in vowels])
You don't have to convert the string to a list. Refer to this answer here:
Correct code to remove the vowels from a string in Python
Because the for statement checks through every letter within the list, even when it removes that vowel. Here's a quick example where it doesn't iterates 3-4 times to remove one vowel:
vowels = ["a", "e", "i", "o", "u"]
def anti_vowel(text):
text1 = list(text.lower())
text1 = [x for x in text1 if x not in vowels]
text2 = "".join(text1)
return (text2)
print anti_vowel("my name is Omar")
print anti_vowel("Hey look Words!")
print anti_vowel("Hey look more Words to look for!")
I am using Python 2.7. I modified your code slightly as follows,
vowels = 'aeiou'
def anti_vowel(text):
text1 = list(text)
print text1
for i in text:
if i.lower() in vowels:
text1.remove(i)
text2 = "".join(text1)
return text2
print anti_vowel("my name is Omar")
#['m', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'O', 'm', 'a', 'r']
#my nm s mr
print anti_vowel("Hey look Words!")
#['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'W', 'o', 'r', 'd', 's', '!']
#Hy lk Wrds!
print anti_vowel("Hey look more Words to look for!")
#['H', 'e', 'y', ' ', 'l', 'o', 'o', 'k', ' ', 'm', 'o', 'r', 'e', ' ', 'W', 'o', 'r', 'd', 's', ' ', 't', 'o', ' ', 'l', 'o', 'o', 'k', ' ', 'f', 'o', 'r', '!']
#Hy lk mr Wrds t lk fr!
I cannot duplicate your problem. The for loop sweeps through the input string once (one character by one character) and removes any vowel encountered. Perhaps you can post your output so we can debug.
This can be done without remove()
#!python2
def anti_vowel(text):
vowels = ["a", "e", "i", "o", "u"]
s1 = ''
for i in text:
if i.lower() in vowels:
pass
else:
s1 += i
return s1
print anti_vowel("my name is Omar")
print anti_vowel("Hey look Words!")
print anti_vowel("Hey look more Words to look for!")

Split string > list of sublists of words and characters

No imports allowed (it's a school assignment).
Wish to split a random string into a list of sublists. Words in a sublist, all other characters (including whitespace) would be in a sublist containing only one item. Anyone have some advice on how to do this;
part = "Hi! Goodmorning, I'm fine."
list = [[H,i],[!],[_],[G,o,o,d,m,o,r,n,i,n,g],[,],[_],[I],['],[m],[_],[f,i,n,e],[.]]
This does the trick:
globalList = []
letters = "abcdefghijklmnopqrstuvwxyz"
message = "Hi! Goodmorning, I'm fine."
sublist = []
for char in message:
#if the character is in the list of letters, append it to the current substring
if char.lower() in letters:
sublist.append(char)
else:
#add the previous sublist (aka word) to globalList, if it is not empty
if sublist:
globalList.append(sublist)
#adds the single non-letter character to the globalList
globalList.append([char])
#initiates a fresh new sublist
sublist = []
print(globalList)
#output is [['H', 'i'], ['!'], [' '], ['G', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g'], [','], [' '], ['I'], ["'"], ['m'], [' '], ['f', 'i', 'n', 'e'], ['.']]
Try this out :
part = "Hi! Goodmorning, I'm fine."
n = part.count(" ")
part = part.split()
k = 0
# Add spaces to the list
for i in range(1,n+1):
part.insert(i+k, "_")
k += 1
new = [] # list to return
for s in part:
new.append([letter for letter in s])
part = "Hi! Goodmorning, I'm fine."
a = []
b = []
c = 0
for i in part:
if i.isalpha():
if c == 1:
a.append(b)
b=[]
b.append(i)
c = 0
else:
b.append(i)
else:
a.append(b)
b=[]
b.append(i)
c = 1
a.append(b)
print a

Splitting the letters of a word based on conditions, and returning in a list (Python)

vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
I'm trying to make a function that would only return constants followed by vowels in a list.
So for example:
f("therapist")
>>>["he", "ra", "pi"]
f("apple")
>>>["le"]
So it's only when a vowel follows a consonant and it returns both the consonant and the vowel in a list.
I was thinking it would be something along the lines of:
def f(word):
for consonant in word:
for vowel in word:
But I don't know how to work with the order and test whether the vowel is after the consonant. Thanks in advance
You can use enumerate with a starting index of 1, checking if the current ele is a consonant and the next chaarcter word[i] is a vowel.
def f(word):
vowels = {"a", "e", "i", "o", "u"}
consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
return [ele + word[i] for i, ele in enumerate(word[:-1], 1)
if word[i] in vowels and ele in consonants ]
Or using loops keep track of the last character and compare:
def f(word):
vowels = {"a", "e", "i", "o", "u"}
consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
pairs = []
it = iter(word)
# get first char
prev = next(it,"")
# iterate over the rest starting at the second char
for ch in it:
# compare prev and current
if prev in consonants and ch in vowels:
pairs.append(prev + ch)
# update prev
prev = ch
return pairs
You can use regex :
>>> import re
>>> def f(s):
... return re.findall(r'[bcdfghjklmnpqrstvwxyz][aeiou]',s)
...
>>> f('therapist')
['he', 'ra', 'pi']
Also you can use zip within a list comprehension :
>>> def f(s):
... return [''.join((i,j)) for i,j in zip(s,s[1:]) if i in 'bcdfghjklmnpqrstvwxyz' and j in 'aeiou']
...
>>> s='therapist'
>>> f(s)
['he', 'ra', 'pi']
Well, you could use a regular expression for this.
I think the real question is: "Does 'y' constitute as a vowel?"
import re
def f(word):
return re.findall('[bcdfghjklmnpqrstvwxyz][aeiou]', word)
print(f("therapist")) # Prints ['he', 'ra', 'pi']
Try this using re
import re
def f(word):
return re.findall(r"(?![aeiou$])\w[aeiou]",word)
>>>f('therapist')
['he', 'ra', 'pi']

Categories

Resources