Where is issue with final display in this code? - python-3.x

The code requires the user to provide an input of strings and convert the uppercase to lower and vice-versa.Input: Rohit Tapadia , Expected Output: rOHIT tAPADIA , Actual Output: rOHIt TAPADIA . It should do exactly what the swapcase() does.
inp = input("Enter ")
for i in inp:
inp_lst.append(i)
print(inp_lst)
for j in inp_lst:
if j.isupper()==True:
x=inp_lst.index(j)
#print(x)
#print(j)
k = j.lower()
#print(k)
inp_lst[x]=k
print(inp_lst[x])
elif j.islower()==True:
y=inp_lst.index(j)
#print(y)
#print(j)
l = j.upper()
inp_lst[y]=l
print(inp_lst[y])
else:
z=inp_lst.index(j)
#print(z)
#print(j)
inp_lst[z]=j
print(inp_lst[z])
print(''.join(inp_lst))```

You can achieve exactly the same thing in 2 lines with the built-in swapcase() method:
inp = input("Enter ")
print(inp.swapcase())
Example input:
heLLo StackOverflow
Output:
HEllO sTACKoVERFLOW
Demo: https://repl.it/#glhr/55548482
Edit: here's a working and simplified implementation of your code. Note that inp_lst is not needed since you can directly iterate over characters in a string. You can simply add each character to the output string using string concatenation (not that outputString += j is equivalent to outputString = outputString + j - it simply adds j at the end of the string).
inp = input("Enter ")
outputString = ""
for j in inp:
if j.isupper():
outputString += j.lower()
elif j.islower():
outputString += j.upper()
else:
outputString += j
print(outputString)
Edit 2: The problem in your code is this inp_lst.index(j), because index() searches for the first occurrence of the character j. So if j='t', it will select the first occurrence of t in the list, and turn it uppercase/lowercase, even if the loop is at the second occurrence of t. That's why the first t in "Rohit Tapadia" is turned to lowercase in the output.

you can try this one too
inp = input("Enter ")
output="".join([char.lower() if char.isupper() else char.upper() for char in inp ])
inp = "Rohit Tapadia"
output will be
rOHIT tAPADIA

Related

How would I print a string obtained from a user in reverse?

I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.
user_string = input("Please enter a string: ")
for letter in (user_string)[::-1]:
print(letter)
You can reverse and use str.join to rebuild the string.
print("\n".join(reversed(input("Please enter a string: "))))
If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:
while i < arr_length:
with i incrementing at the end of every round.
The rest of the code would be the same but using i as an index.
One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.
user_input = list(input())
while len(user_input) > 0:
print(user_input.pop())
list.pop() will remove the last item in the list and return it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Using index property we can easily reverse a given string
a = input()
print(a[::-1])

Concatenating string outputs of a for loop in Python 3

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)

pig latin issues with output code for python

I am having trouble with the code only producing the first two letters of the first word and then attaching the 'AY' to the end while it runs. I can't seem to figure out how to correct this error.
def main():
strin = input('Enter a sentence (English): ')
strlist = strin.split()
i = 0
pigsen = ''
while i < len(strlist):
word = strlist[i]
j = 1
fc = word[0].upper()
pigword =''
while j < len(word):
pigword += word[j].upper()
j += 1
pigword += fc + 'AY'
pigsen += pigword + ' '
i +=1
print('Pig Latin: ' +str(pigsen))
main()
First, I'll assume this is just the start of a pig Latin generator and you'll add the other rules (at least a couple more) once you get this much working. Second, let's simplify the code as a way of fixing it:
def main():
sentence = input('Enter a sentence (English): ')
words = sentence.upper().split()
latin_words = []
for word in words:
first, rest = word[0], word[1:]
latin_word = rest + first + 'AY'
latin_words.append(latin_word)
print('Pig Latin:', *latin_words)
main()
USAGE
> python3 test.py
Enter a sentence (English): He complimented me on my English
Pig Latin: EHAY OMPLIMENTEDCAY EMAY NOAY YMAY NGLISHEAY
>
I would say the problem with your code is you made it too complicated.

Print all words in a String without split() function

I want to print out all words in a string, line by line without using split() funcion in Python 3.
The phrase is a str(input) by the user, and it has to print all the words in the string, no matter it's size.Here's my code:
my_string = str(input("Phrase: "))
tam = len(my_string)
s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
if letter == ch:
#print(i)
print(my_string[cont:i])
cont+=i+1
The output to this is:
Phrase: Hello there my friend
Hello
there
It is printing only two words in the string, and I need it to print all the words , line by line.
My apologies, if this isn't a homework question, but I will leave you to figure out the why.
a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend
Some variants you can add to the process which you can't get easily with if-else syntax:
print(b.Title()) # b.lower() or b.upper()
Hello
There
My
Friend
def break_words(x):
x = x + " " #the extra space after x is nessesary for more than two word strings
strng = ""
for i in x: #iterate through the string
if i != " ": #if char is not a space
strng = strng+i #assign it to another string
else:
print(strng) #print that new string
strng = "" #reset new string
break_words("hell o world")
output:
hell
o
world

Combining two strings to form a new string

I am trying to write a program that asks the user for two strings and creates a new string by merging the two together (take one letter from each string at a time). I am not allowed to use slicing. If the user enters abcdef and xyzw, program should build the string: axbyczdwef
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
i = 0
print("The new string is: ",end='')
while i < len(s1):
print(s1[i] + s2[i],end='')
i += 1
The problem I am having is if one of the strings is longer than the other I get an index error.
You need to do your while i < min(len(s1), len(s2)), and then make sure to print out the remaining part of the string.
OR
while i < MAX(len(s1), len(s2)) and then only print s1[i] if len(s1) > i and only print s2[i] if len(s2) > i in your loop.
I think zip_longest in Python 3's itertools gives you the most elegant answer here:
import itertools
s1 = input("Enter a string: ")
s2 = input("Enter a string: ")
print("The new string is: {}".format(
''.join(i+j for i,j in itertools.zip_longest(s1, s2, fillvalue=''))))
Here's the docs, with what zip_longest is doing behind the scenes.

Resources