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)
Related
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")
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])
For this problem, I am given strings ThatAreLikeThis where there are no spaces between words and the 1st letter of each word is capitalized. My task is to lowercase each capital letter and add spaces between words. The following is my code. What I'm doing there is using a while loop nested inside a for-loop. I've turned the string into a list and check if the capital letter is the 1st letter or not. If so, all I do is make the letter lowercase and if it isn't the first letter, I do the same thing but insert a space before it.
def amendTheSentence(s):
s_list = list(s)
for i in range(len(s_list)):
while(s_list[i].isupper()):
if (i == 0):
s_list[i].lower()
else:
s_list.insert(i-1, " ")
s_list[i].lower()
return ''.join(s_list)
However, for the test case, this is the behavior:
Input: s: "CodesignalIsAwesome"
Output: undefined
Expected Output: "codesignal is awesome"
Console Output: Empty
You can use re.sub for this:
re.sub(r'(?<!\b)([A-Z])', ' \\1', s)
Code:
import re
def amendTheSentence(s):
return re.sub(r'(?<!\b)([A-Z])', ' \\1', s).lower()
On run:
>>> amendTheSentence('GoForPhone')
go for phone
Try this:
def amendTheSentence(s):
start = 0
string = ""
for i in range(1, len(s)):
if s[i].isupper():
string += (s[start:i] + " ")
start = i
string += s[start:]
return string.lower()
print(amendTheSentence("CodesignalIsAwesome"))
print(amendTheSentence("ThatAreLikeThis"))
Output:
codesignal is awesome
that are like this
def amendTheSentence(s):
new_sentence=''
for char in s:
if char.isupper():
new_sentence=new_sentence + ' ' + char.lower()
else:
new_sentence=new_sentence + char
return new_sentence
new_sentence=amendTheSentence("CodesignalIsAwesome")
print (new_sentence)
result is codesignal is awesome
I'm making a text converter, and I'd like to select random characters in a string that already exists.
When I research it, all that comes up is someone that wants to generate random letters in the alphabet or someone that wants to generate a random string. That's not what I'm looking for.
new_string = ""
index = 0
for letter in input_text:
if letter not in "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM":
new_string = new_string + (letter)
continue
index += 1
if index % 2 == 0:
new_string = new_string + (letter.upper())
else:
new_string = new_string + (letter.lower())
My existing text converter capitalizes every other letter, but I'd like to have it randomly capitalize the letters. Is this possible?
You may want to look at the random.choice and random.choices functions in the random library (built-in), which allows you to randomly select an item from a list:
>>> import random
>>> a = random.choice("ABCDabcd")
'C'
>>> my_text = "".join(random.choices("ABCDabcd", k=10))
'baDdbAdDDb'
In order to randomly capitalize, you can choice from a list of the lower- and upper-case version of a letter:
import random
new_string = ""
for letter in input_text:
if letter not in "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM":
new_string = new_string + (letter)
else:
new_string += random.choice([letter.upper(), letter.lower()])
(Note that random.choices returns a list, not a str, so we need to join() the elements together.)
Finally, you may also want to use the isalpha function:
>>> "A".isalpha()
True
>>> "a".isalpha()
True
>>> "7".isalpha()
False
(Relevant question)
But upper() and lower() functions have no effect on non-alpha characters. So you can completely remove this check from your code:
new_string = ""
for letter in input_text:
new_string += random.choice([letter.upper(), letter.lower()])
I'm doing a function that give the number of words in a sentence.
Example: " Hello L World " there are 3 "words" (A letter is counted like a word).
Here is my code:
def number_of_word(s):
"""
str -> int
"""
# i : int
i = 0
# nb_word : int
nb_word = 0
if s == "":
return 0
else:
while i < len(s)-1:
if ((s[i] != " ") and (s[i+1] == " ")):
nb_word = nb_word + 1
i = i + 1
else:
i = i + 1
if s[len(s)-1] != " ":
nb_word = nb_word + 1
return nb_word
else:
return nb_word
I tried my function and I think it works. But, I also think there is a better way to do a function that do the same thing in an easier way.
Can you tell me if you know one better function? Or any comments on mine?
I hade to use:
if s == "":
return 0
else:
...........
because if I didn't, my function didn't work for number_of_word("")
If you define words as character sequences separated by one or more whitespaces, then you can simply use the split method of strings to split to words,
and then len to get their count:
def number_of_word(s):
return len(s.split())
From the documentation (emphasis mine):
split(...) method of builtins.str instance
S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done. If sep is not
specified or is None, any whitespace string is a separator and empty
strings are removed from the result.
If you want you can use RegExp
import re
def number_of_word(s):
pattern = r'\b\w+\b'
return len(re.findall(pattern, s))
If you can't use split or regex, I think this is the right solution:
def count(sentence):
wlist = []
word = ""
for c in sentence:
if c == " ":
wlist.append(word)
word = ""
else:
word += c
wlist.append(word)
return len(wlist)
You can use split() method :
def count(string1):
string1=string1.split()
return len(string1)
print(count(" Hello L World "))
output:
3
I can't use more python' functions than just "len".
So, I can't use split or RegExp.
So I want to make this function with just basic code and len.
Well, since the requirements were published, here's a way to do this without calling any library functions:
def count_words(sentence):
count, white = 0, True
for character in sentence:
if character not in " \t\n\r":
if white:
count += 1
white = False
else:
white = True
return count