Concatenating string outputs of a for loop in Python 3 - python-3.x

I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?

You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)

Related

Problem with Python Code and the Functions in it

I have a Problem, I have to solve a task in Python and I dont know how to do it. The task is to define a function number_of_vowels, where the output should be the Number of vowels in a Word. With this function I have to write anotherone, many_vowels thats working with a list an a Number and where the number says how many vowels have to be at least in a word to be appended to the result list and then I have to append this Word. Thanks to everybody helping me ;D.
here is the code:
Wort = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
while result < 20:
if Word[counter0] == 'a' or 'e' or 'i' or 'o' or 'u':
result = result + 1
counter0 = counter0 + 1
else:
counter0 = counter0 + 1
return result
Words = []
counter1 = 0
def many_vowels(List , number):
if number_of_vowels(List[counter1]) < number:
counter1 + 1
else:
Words.append(List[counter1])
counter1 + 1
return Words
This code just gives me the answer to the letter a and not to the other vowels. For
print(number_of_vowels(Wort))
the output is: 1
but there are 4 vowels in this word
it also says: line 21, in many_vowels
IndexError: string index out of range
You're trying to call a function with wrong brackets. Function call should use round ones.
Try changing number_of_vowels[List[counter1]] with number_of_vowels(List[counter1])
This code contains some errors:
Calling for function should be using round brackets: number_of_vowels(List[counter1]) instead of number_of_vowels[List[counter1]]
doing result + 1 won't change value of the variable result, since you did not put the calculation result in the variable. use result = result + 1 (same for counters)
in number_of_vowels function, you want to scan the whole word? cause you did not use any loop, so it currently looking only at the first letter. Secondly, you put the compression in result and then add 1 to it. I'm not really sure why
edit:
Word = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
for index, letter in enumerate(Word):
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
result = result + 1
return result
Words = []
counter1 = 0
def many_vowels(List_name , number):
for index, item in enumerate (List_name):
if number_of_vowels(item) >= number:
Words.append(item)
return Words

How can I find a string in sequence (with Booleans)?

I receive a String. For example in here I have :
Mystring= ‘alohrefllluqoo’
I can see all the letter of 'Hello' word, in the correct sequence, in Mystring string
is it possible to use Booleans?
in that string the final output would be 'YES', cause when I remove extra letter I can see the 'Hello' word (in correct sequence) in string.
and if the sequence is not correct and the word can not be found, the output will be 'NO'
This is one approach.
Ex:
Mystring= 'alohrefllluqoo'
to_find = "hello"
def check_string(Mystring, to_find):
c = 0
for i in Mystring:
if i == to_find[c]:
c += 1
if c == len(to_find):
return "YES"
return "NO"
print(check_string(Mystring, to_find))
You can use something like this:
mystring = 'alohreflllouq'
wordtofind = "hello"
i=0
word=''
for char in mystring:
if char == wordtofind[i]:
word = word + char
i+= 1
if word == wordtofind:
break
result = "YES" if word == wordtofind else "NO"
print(result)
making a function, and passing your string, and the thing you search for:
def IsItHere(some_string, sub_string)
try:
some_string.index(sub_string)
return 'YES'
except:
return 'NO'

Statement has no effect(Python)

program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t'
here's my code
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t:
each == '$'
else:
continue
return string
print(change("restart"))
output
restart
i'using Pycharm. Line no 6 (each == '$')says this statement has no effect. i don't want to use replace method. just want to know what is the problem.
Your code commented:
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t: # To compara strings you should use the == operator not the 'is' operator.
each == '$' # This will not have any effect because is a temporal variable visible just inside the 'for' loop and you are not using it.
else:
continue
return string
print(change("restart"))
A solution could be:
def change(s):
result = ''
for character in s:
result += '$' if character == s[0] else character
return result
print(change('restart'))
Python strings are immutable objects, so you can't do 'aaa'[1] = 'b' to get aba.
each is set to an integer and you are comparing it to a string.

Reverse loop for palindrome

My teacher wants me to use a reverse loop instead of the reverse function I am using right now. I can't seem to get one that works.
def palindrome():
myInput = input("Enter a Word: ")
word = myInput[::-1]
if myInput == word:
print("That is a palindrome")
return True
else:
print("That is not a palindrome")
return False
palindrome()
def palindrome():
string = input("Enter a Word: ")
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True
Edited for below comment:
the enumerate() function adds a counter to an iterable.
>>> string = "PARAM"
>>> for count, elem in enumerate(string):
... print count, elem
...
0 P
1 A
2 R
3 A
4 M
so line if char != string[-i-1] will try to match one character from front and one character from end.
You could try the code below, but I really recommend you to try it yourself first. (Because, if you're able to write a recursive call, you should be able to write an iterative one yourself too.)
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final

How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string

def shortenPlus(s) -> "s without some vowels":
for char in s:
if char in "AEIOUaeiou":
return(s.replace(char,""))
I have the taken it out of the entire string. But I can't figure out how to restrict the replace function to everything but the first letter of each word in a string.
Not sure exactly what you're looking for, can you clarify, perhaps give a simple example? None of the words you have in your example start with vowels!
But here you could remove all the vowels in a word except the first vowel of the first word. Hard coded but gives you an idea:
s="without some vowels"
for char in s[2:]:
if char in "AEIOUaeiou":
s=s.replace(char,"")
print(s)
Outputs
witht sm vwls
Alternatively, to get the first char of every word, you could use a sentinel value that flags each time a non-alpha char such as punctuation or a space is present, then keeps the next char but not the others.
s="without some vowels"
sent=2
for char in s:
if sent>0:
sent-=1
print(char)
continue
if not char.isalpha():
sent=2
continue
s=s.replace(char,"")
print(output)
Outputs
w s v
def shortenPlus(s):
counter = 0 # accepted character count
add_the_vowel = True # check if vowel came for the first time for the word
temp = " " # temp string to store the output
for letter in s:
if letter == " ":
add_the_vowel= True
if add_the_vowel == True and letter in "AEIOUaeiou":
temp += s[counter] # first vowel of the word
if letter in "AEIOUaeiou":
add_the_vowel = False # restrict second vowel appeared
else:
temp += s[counter]
counter += 1
print(temp)
s = "without some vowels frienis"
shortenPlus(s)
How to keep the vowel at the beginning of all the words in a string, but remove in the rest of the string
output :
witht som vowls frins

Resources