printing . before every character in a string - python

I have a string and it's "java is fun for sure" and i want to print
delete every vowel letters(aeiou)
print a "." before every character
so the out come would be like ".j.v. .s. .f.n. .f.r. .s.r"
I have tried this
s = str(input())
s.translate({ord(i): None for i in 'aeiou '})
the outcome is "jvsfnfrsr" but i don't know how to print "." before the letters.
Some help would be awesome! I'm sure this is a very simple issue, but for some reason i cannot come up with it!
Thx in advance! :)

import re
s = str(input())
s = s.translate({ord(i): None for i in 'aeiouAEIOU'})
print(re.sub('([^\s])', r'.\1', s))
Input: "java is fun for sure"
Output: ".j.v .s .f.n .f.r .s.r"
A solution using regex

You can use the 3-param version of maketrans to create the needed translation dictionary. Use the the sep param of print(..) to place the .:
s = "java is fun for sure"
s1 = s.translate(str.maketrans("", "", "aeiou")) # AEIOU are kept as is
print("", *s.translate(str.maketrans("", "", "aeiou")), sep=".")
or in short:
print("",*"java is fun for sure".translate(str.maketrans("", "", "aeiou")),sep=".")
The * before the string-var decomposes the string into its letters:
print(*"abc", sep = "#") # == print("a","b","c", sep = "#")
Output:
.j.v. .s. .f.n. .f.r. .s.r
If you need the resulting string you can use str.join():
s2 = '.' + '.'.join(s1)

What about this? It retains capitalised letters also.
vowels = 'aeiouAEIOU'
tmp = ''.join([char for char in str1 if char not in vowels])
final = ''.join(['.'+char for char in tmp])

Related

Python String adjust

Hello is use some method like .isupper() in a loop, or string[i+1] to find my lower char but i don't know how to do that
input in function -> "ThisIsMyChar"
expected -> "This is my char"
I´ve done it with regex, could be done with less code but my intention is readable
import re
def split_by_upper(input_string):
pattern = r'[A-Z][a-z]*'
matches = re.findall(pattern, input_string)
if (matches):
output = matches[0]
for word in matches[1:]:
output += ' ' + word[0].lower() + word[1:]
return output
else:
return input_string
print(split_by_upper("ThisIsMyChar"))
>> split_by_upper() -> "This is my char"
You could use re.findall and str.lower:
>>> import re
>>> s = 'ThisIsMyChar'
>>> ' '.join(w.lower() if i >= 1 else w for i, w in enumerate(re.findall('.[^A-Z]*', s)))
'This is my char'
You should first try by yourself. If you didn't get it done, you can do something like this:
# to parse input string
def parse(str):
result= "" + str[0];
for i in range(1, len(str)):
ch = str[i]
if ch.isupper():
result += " ";
result += ch.lower();
return result;
# input string
str = "ThisIsMyChar";
print(parse(str))
First you need to run a for loop and check for Uppercase words then when you find it just add a space at the starting, lower the word and increment it to your new string. Simple, more code is explained in comments in the code itself.
def AddSpaceInTitleCaseString(string):
NewStr = ""
# Check for Uppercase string in the input string char-by-char.
for i in string:
# If it found one, add it to the NewStr variable with a space and lowering it's case.
if i.isupper(): NewStr += f" {i.lower()}"
# Else just add it as usual.
else: NewStr += i
# Before returning the NewStr, remove all the leading and trailing spaces from it.
# And as shown in your question I'm assuming that you want the first letter or your new sentence,
# to be in uppercase so just use 'capitalize' function for it.
return NewStr.strip().capitalize()
# Test.
MyStr = AddSpaceInTitleCaseString("ThisIsMyChar")
print(MyStr)
# Output: "This is my char"
Hope it helped :)
Here is a concise regex solution:
import re
capital_letter_pattern = re.compile(r'(?!^)[A-Z]')
def add_spaces(string):
return capital_letter_pattern.sub(lambda match: ' ' + match[0].lower(), string)
if __name__ == '__main__':
print(add_spaces('ThisIsMyChar'))
The pattern searches for capital letters ([A-Z]), and the (?!^) is negative lookahead that excludes the first character of the input ((?!foo) means "don't match foo, ^ is "start of line", so (?!^) is "don't match start of line").
The .sub(...) method of a pattern is usually used like pattern.sub('new text', 'my input string that I want changed'). You can also use a function in place of 'new text', in which case the function is called with the match object as an argument, and the value returned by the function is used as the replacement string.
The expression capital_letter_pattern.sub(lambda match: ' ' + match[0].lower(), string) replaces all matches (all capital letters except at the start of the line) using a lambda function to add a space before and make the letter lowercase. match[0] means "the entirety of the matched text", which in this case is the captial letter.
You can split it via Regex using r"(?<!^)(?=[A-Z])" pattern:
import re
txt = 'ThisIsMyChar'
c = re.compile(r"(?<!^)(?=[A-Z])")
first, *rest = map(str.lower, c.split(txt))
print(f'{first.title()} {" ".join(rest)}')
Pattern explanation:
(?<!^) checks to see if it is not at the beginning.
(?=[A-Z]) checks to see there a capital letter after it.
note These are non-capturing groups.

change more characters in python 3

my problem is the follow:
I ask a string from somebody (for example: This is the text):
a = input("Enter a text: "))
I would like the change every vowel like this: e->eve, a->ava, i->ivi, u->uvu, o->ovo with for cycle
Finally I would print the new text
My solution is:
b = a.replace('o', 'ovo').replace('u', 'uvu')
print(b)
But this does not use the for cycle
could you help me, please? Thanks!
You can loop through a string in Python with for c in "string":
Using this, you could solve your problem by
newString=""
for c in a:
if c in ["a", "e", "i", "o" "u", "y"]:
newString+=c+"v"+c
else:
newString+=c
I assume by for-cycle you mean for loop?
For this transformation you can use a lookup-dictionary in combination with a for-loop. Two toy examples:
transforms = {'a':'ava',
'e':'eve',
'i':'ivi',
'u':'uvu',
'o':'ovo'}
test_string = 'This is some text'
First you can create a new string with the replaced words:
new_string = ''
for char in test_string:
if char in transforms:
new_string += transforms[char]
else:
new_string += char
Which yields 'Thivis ivis sovomeve tevext'.
Or you may convert the original to a list and replace elements using the dictionary (and finally join your list):
test_string = list(test_string)
for i, ch in enumerate(test_string):
if ch in transforms:
test_string[i] = transforms[ch]
test_string = ''.join(test_string)
Which also yields 'Thivis ivis sovomeve tevext'
for c in ('a','e','i','o','u'):
a = a.replace(c, c+'v'+c)
print(a)
You can create a previous copy of a if you need the original string.
Thank you all! The whole solution is:
transforms = {'a':'ava',
'e':'eve',
'i':'ivi',
'u':'uvu',
'o':'ovo',
'ö':'övö',
'ü':'üvü',
'ó':'óvó',
'ő':'ővő',
'ú':'úvú',
'é':'évé',
'á':'ává',
'ű':'űvű',
'í':'ívi'}
test_string = input('Írj be egy tetszőleges szöveget, amit ivigyelek: ')
new_string = ''
for char in test_string:
if char in transforms:
new_string += transforms[char]
else:
new_string += char
print(new_string)

How add "." before each letter in string

as title says i simply need to add a . before each letter in my string
while having vowels removed and making it lowercase
i got it working just cant add the .s there
here is my code
s = str(input())
vowels = ('a','e','o','u','i','A','E','O','U','I')
for letter in s:
if letter in vowels:
s = s.replace(letter,'').replace()
print(s)
Use:
s = input()
vowels = set('aeoui')
print(''.join([f'.{x}' for x in s.lower() if x not in vowels]))
Sample run:
Hello
.h.l.l
All other answers will insert a . in front of every character in the string, but you specified that you want letters only. So I am assuming that you only want a-z to be prepended with a . for which I suggest re.sub:
import re
s = "This is some test string. It contains some symbols also ()!!"
result = re.sub('[aeoui]', '', s.lower()) # remove vowels and make lowercase
result = re.sub("([a-z])", r".\1", result) # prepend '.' to every letter
print(result)
Outputs:
.t.h.s .s .s.m .t.s.t .s.t.r.n.g. .t .c.n.t.n.s .s.m .s.y.m.b.l.s .l.s ()!!
You can do it step by step:
Replace all the vowels in the string with ''
for i in s:
for j in vowels:
s=s.replace(j,'')
Convert the string into lowercase:
s=s.lower()
Adding '.' in between each letters:
s='.' + '.'.join(s)

Remove extra characters in the string in Python

I have couple of strings (each string is a set of words) which has special characters in them. I know using strip() function, we can remove all occurrences of only one specific character from any string. Now, I would like to remove set of special characters (include !##%&*()[]{}/?<> ) etc.
What is the best way you can get these unwanted characters removed from the strings.
in-str = "#John, It's a fantastic #week-end%, How about () you"
out-str = "John, It's a fantastic week-end, How about you"
import string
s = "#John, It's a fantastic #week-end%, How about () you"
for c in "!##%&*()[]{}/?<>":
s = string.replace(s, c, "")
print s
prints "John, It's a fantastic week-end, How about you"
The strip function removes only leading and trailing characters.
For your purpose I would use python set to store your characters, iterate over your input string and create new string from characters not present in the set. According to other stackoverflow article this should be efficient. At the end, just remove double spaces by clever " ".join(output_string.split()) construction.
char_set = set("!##%&*()[]{}/?<>")
input_string = "#John, It's a fantastic #week-end%, How about () you"
output_string = ""
for i in range(0, len(input_string)):
if not input_string[i] in char_set:
output_string += input_string[i]
output_string = " ".join(output_string.split())
print output_string
Try out this:
import re
foo = 'a..!b...c???d;;'
chars = [',', '!', '.', ';', '?']
print re.sub('[%s]' % ''.join(chars), '', foo)
I presume that this is what you wanted.
try
s = "#John, It's a fantastic #week-end%, How about () you"
chars = "!##%&*()[]{}/?<>"
s_no_chars = "".join([k for k in s if k not in chars])
s_no_chars_spaces = " ".join([ d for d in "".join([k for k in s if k not in chars]).split(" ") if d])

String reverse in Python

Write a simple program that reads a line from the keyboard and outputs the same line where
every word is reversed. A word is defined as a continuous sequence of alphanumeric characters
or hyphen (‘-’). For instance, if the input is
“Can you help me!”
the output should be
“naC uoy pleh em!”
I just tryed with the following code, but there are some problem with it,
print"Enter the string:"
str1=raw_input()
print (' '.join((str1[::-1]).split(' ')[::-2]))
It prints "naC uoy pleh !em", just look the exclamation(!), it is the problem here. Anybody can help me???
The easiest is probably to use the re module to split the string:
import re
pattern = re.compile('(\W)')
string = raw_input('Enter the string: ')
print ''.join(x[::-1] for x in pattern.split(string))
When run, you get:
Enter the string: Can you help me!
naC uoy pleh em!
You could use re.sub() to find each word and reverse it:
In [8]: import re
In [9]: s = "Can you help me!"
In [10]: re.sub(r'[-\w]+', lambda w:w.group()[::-1], s)
Out[10]: 'naC uoy pleh em!'
My answer, more verbose though. It handles more than one punctuation mark at the end as well as punctuation marks within the sentence.
import string
import re
valid_punctuation = string.punctuation.replace('-', '')
word_pattern = re.compile(r'([\w|-]+)([' + valid_punctuation + ']*)$')
# reverses word. ignores punctuation at the end.
# assumes a single word (i.e. no spaces)
def word_reverse(w):
m = re.match(word_pattern, w)
return ''.join(reversed(m.groups(1)[0])) + m.groups(1)[1]
def sentence_reverse(s):
return ' '.join([word_reverse(w) for w in re.split(r'\s+', s)])
str1 = raw_input('Enter the sentence: ')
print sentence_reverse(str1)
Simple solution without using re module:
print 'Enter the string:'
string = raw_input()
line = word = ''
for char in string:
if char.isalnum() or char == '-':
word = char + word
else:
if word:
line += word
word = ''
line += char
print line + word
you can do this.
print"Enter the string:"
str1=raw_input()
print( ' '.join(str1[::-1].split(' ')[::-1]) )
or then, this
print(' '.join([w[::-1] for w in a.split(' ') ]))

Categories