Append dot before each letters - python

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())

Related

Python ignore punctuation and white space

string = "Python, program!"
result = []
for x in string:
if x not in result:
result.append(x)
print(result)
This program makes it so if a repeat letter is used twice in a string, it'll appear only once in the list. In this case, the string "Python, program!" will appear as
['P', 'y', 't', 'h', 'o', 'n', ',', ' ', 'p', 'r', 'g', 'a', 'm', '!']
My question is, how do I make it so the program ignores punctuation such as ". , ; ? ! -", and also white spaces? So the final output would look like this instead:
['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']
Just check if the string (letter) is alphanumeric using str.isalnum as an additional condition before appending the character to the list:
string = "Python, program!"
result = []
for x in string:
if x.isalnum() and x not in result:
result.append(x)
print(result)
Output:
['P', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'g', 'a', 'm']
If you don't want numbers in your output, try str.isalpha() instead (returns True if the character is alphabetic).
You can filler them out using the string module. This build in library contains several constants that refer to collections of characters in order, like letters and whitespace.
import string
start = "Python, program!" #Can't name it string since that's the module's name
result = []
for x in start:
if x not in result and (x in string.ascii_letters):
result.append(x)
print(result)

Inserting breaks in variables over a certain length

So basically what I want to do is if the random string of characters generated is over 6 chars long it adds a space in a random place in that string and then the remaining ones are added on after the space so for example: raw output: "aoneicse", what I want : "aoneic se" or "aone icse".
Here is my code:
import random
alist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
blist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
clist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# define the 3 words
a = ''.join(random.choices(alist, k = random.randint(2,8)))
b = ''.join(random.choices(blist, k = random.randint(2,8)))
c = ''.join(random.choices(clist, k = random.randint(2,8)))
# each letter is a certain word, if this word exceeds 6 characters add a space in a random place
if a length = > 6:
asp = [a + " "]
if b length = > 6:
bsp = [b + " "]
if c length = > 6:
csp = [c + " "]
# or something along the lines of this i guess
This code does not currently work, BTW.
You don't need to create a list of strings with every letter of the alphabet, there's already a string module that does that for you:
import string
print(' ' + string.ascii_lowercase)
# Outputs abcdefghijklmnopqrstuvwxyz
You also don't need to create three different variables, you can just use a single one and use that:
import string
base_str = ' ' + string.ascii_lowercase
Then, you can use a list to generate your words based on this string:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
Now, just apply your space requirement to each word:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
new_words = []
for word in words:
if len(word) < 6:
new_word = word
else:
pos = random.randrange(len(word))
new_word = word[:pos] + ' ' + word[pos:]
new_words.append(new_word)
Using random.seed(0), new_words is equal to ['j xazmxvz', 'oxmg', 'buzns pcb'].
Don't join the choices immediately. Generate the list, and if it is long enough, pick an index in the middle (sufficiently far from either end, depending on your needs), and perform a slice assignment to the empty list at that position. Then join the list into a single string.
import string
a = random.choices(string.ascii_lowercase, k=random.randint(2,8))
if len(a) > 6:
# Adjust the arguments to randint as desired
x = random.randint(2, len(a) - 2)
a[x:x] = ' '
a = ''.join(a)
import random
character = list(map(chr, range(ord('a'), ord('z') + 1)))
def get_char():
return character[random.randint(0, len(character) - 1)]
def gen_word(min_len, max_len):
word = [get_char() for _ in range(random.randint(min_len, max_len))]
if len(word) > 6:
word[random.randint(1, len(word) - 2)] = ' '
return ''.join(word)
for i in range(10):
print(gen_word(4, 10))
I’d use slices to return a space, sliced-in at the right spot; Something along the lines of:
def split(input_str):
if len(input_str) > 6:
space_at = rand(0,len(input_str))
return input_str[:space_at] + ‘ ‘ + input_str[space_at:]
else:
return input_str

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')

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!")

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