How would I print a string obtained from a user in reverse? - python-3.x

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

Related

Python string comparison function with input, while loop, and if/else statment

I'm trying to create a program that takes input from the user, -1 or 1 to play or quit, number of characters (n), two words for comparison (s1,s2), and calls this function: def strNcompare (s1,s2,n) and then prints the result. The function should return 0,-1,1 if n-character portion of s1 is equal to, less than, or greater than the corresponding n-character of s2, respectively. So for example is the first string is equal to the second string, it should return a 0.
The loop should end when the user enters, -1.
I'm just starting out in Python so the code I have is pretty rough. I know I need an if/else statement to print the results using the return value of the function and a while loop to make the program run.
This is what I have so far, it by no means works but my knowledge ends here. I don't know how to integrate the character (n) piece at all either.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = int(input("number of characters: ")
s1 = s1[:n]
s1 = s2[:n]
if com==-1:
break
def strNcompare(s1,s2,n):
return s1==s2
elif s1==s2:
print(f'{s1} is equal to {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("QUIT")
break
com = input ("String comparison [1(play), -1(quit)]: ")
As of 10/05/2019 - I revised the code and now I am getting a syntax error at "s1 = s1[:n]"
it did not made much sense and especially the variable 'n' is not completely clear to me. I would not code it like that but I tried to be as close to your logic as possible.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = input ("number of characters: ") #what is the purpose of this?
if s1==s2:
print(f'{s1} is equal than {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("Error")

python3.7 - NameError: name 'paul' is not defined using

tekst = input("Enter your word: ")
for i in len(tekst):
if tekst(i) == tekst(-i):
print(tekst + " is a palindrome word")
else:
print( tekst + " is not a palindrome word")
Having some trouble with the input, I am using python 3.7.
you are using () instead of [] to access the string characters.
tekst(i) would mean that you are calling a function named tekst and passing i to it, where as tekst[i] is used to address specific element in array.
so this
if tekst(i) == tekst(-i):
should be
if tekst[i] == tekst[-i]:
another way to check for palindrome is
if (tekst == tekst[::-1]):
You just messed up the syntax. The subscript operator is [], which is used to access any element in a list or a string.
tekst is a string, the ith member of the string can be accessed using tekst[i]. Instead, you have used tekst(i) which means you are trying to call a function named tekst, which does not exist. Hence the NameError.
So far you can check the below code to correct the syntax. Remember that indentation for Python play very important role which has not been correctly used by your code. You have to use here [].
tekst = input("Enter your word: ")
for i in range(len(tekst)):
if tekst[-i] == tekst[-i]:
print(tekst + " is a palindrome word")
else:
print( tekst + " is not a palindrome word")
You can check the live demo here- Demo
To know how to write program for checking if a string is palindrome or not use the link here

hello friends i cant execute my else condition

The program must accept a string S as the input. The program must replace every vowel in the string S by the next consonant (alphabetical order) and replace every consonant in the string S by the next vowel (alphabetical order). Finally, the program must print the modified string as the output.
s=input()
z=[let for let in s]
alpa="abcdefghijklmnopqrstuvwxyz"
a=[let for let in alpa]
v="aeiou"
vow=[let for let in v]
for let in z:
if(let=="a"or let=="e" or let=="i" or let=="o" or let=="u"):
index=a.index(let)+1
if index!="a"or index!="e"or index!="i"or index!="o"or index!="u":
print(a[index],end="")
else:
for let in alpa:
ind=alpa.index(let)
i=ind+1
if(i=="a"or i=="e" or i=="i"or i=="o"or i=="u"):
print(i,end="")
the output is :
i/p orange
pbf
the required output is:
i/p orange
puboif
I would do it like this:
import string
def dumb_encrypt(text, vowels='aeiou'):
result = ''
for char in text:
i = string.ascii_letters.index(char)
if char.lower() in vowels:
result += string.ascii_letters[(i + 1) % len(string.ascii_letters)]
else:
c = 'a'
for c in vowels:
if string.ascii_letters.index(c) > i:
break
result += c
return result
print(dumb_encrypt('orange'))
# puboif
Basically, I would use string.ascii_letters, instead of defining that anew. Also, I would not convert all to list as it is not necessary for looping through. The consonants you got right. The vowels, I would just do an uncertain search for the next valid consonant. If the search, fails it sticks back to default a value.
Here I use groupby to split the alphabet into runs of vowels and consonants. I then create a mapping of letters to the next letter of the other type (ignoring the final consonants in the alphabet). I then use str.maketrans to build a translation table I can pass to str.translate to convert the string.
from itertools import groupby
from string import ascii_lowercase as letters
vowels = "aeiou"
is_vowel = vowels.__contains__
partitions = [list(g) for k, g in groupby(letters, is_vowel)]
mapping = {}
for curr_letters, next_letters in zip(partitions, partitions[1:]):
for letter in curr_letters:
mapping[letter] = next_letters[0]
table = str.maketrans(mapping)
"orange".translate(table)
# 'puboif'

Python lists and ranges

I'm trying to practice my python so I can improve. I'm kinda stuck and not sure how to proceed. I get an error saying "can only concatenate list(not 'int') to list." I'll leave my code and what I'm trying to do below.
Input a word string (word)
find the string length of word
use range() to iterate through each letter in word (can use to range loops)
Save odd and even letters from the word as lists
odd_letters: starting at index 0,2,...
even_letters: starting at index 1,3,...
print odd and even lists
word = input("Type: ")
word = list(word)
print(word)
odd_letters = []
even_letters = []
length = int(len(word))
for i in range(length):
if i/2 == 0:
even_letters = even_letters + i
elif i/2 != 0:
odd_letters = odd_letters + i
print(even_letters)
print(odd_letters)
I wrote this... Let me know what you think...
word = input("Choose a word to test: ")
word_len = len(word)
print(word," contains ",word_len," letters")
odd_letters = []
even_letters = []
for i in range(1,len(word),2):
even_letters.append(word[i])
for i in range(0,word_len,2):
odd_letters.append(word[i])
print("Odd letters are: ",odd_letters)
print("Even letters are: ",even_letters)
Your code is good, but i decided to find a quicker solution for the program you want. This is my code:
word = str(input("Enter word:"))
store_1 = [x for x in word]
store_2 = []
for idx, val in enumerate(store_1):
store_2.append(idx)
even_numbers = [y for y in store_2 if y%2 == 0]
odd_numbers = [z for z in store_2 if z%2 == 1]
print("List of Even numbers:",even_numbers)
print("List of Odd numbers:",odd_numbers)
The variable 'word' takes in the word from the user. The list 'store_1' uses list comprehension to separate the letters the in the word and store it. Next, i enumerate through 'store_1' and use the variable 'store_2' to only store the indexes of 'store_1'.
Next, I declare another variable 'even_numbers' that uses list comprehension to iterate through 'store_2' and find the even numbers. The next variable 'odd_numbers' also uses list comprehension to find the odd numbers in 'store_2'.
Then, it just prints the even and odd lists to the user. Hope this helps :)
You cannot add an integer to a list, as you have attempted to do here:
even_letters = even_letters + i
You can instead do this (which is now adding a list to a list, which is valid):
even_letters = even_letters + [i]
Or, use append to alter the list in-place, adding the new element to the end:
even_letters.append(i)
Few things:
You cannot "add" an integer directly to a list using '+'. Using append() would be best.
str and str types can be concatenated using '+' so you could change odd_letters and even_letters to str as shown below.
also, by adding 'i' to even and odd, you are adding the iteration variable value.
Since you want the letter to be appended, you need to refer the list index i.e word[i]
and the first letter of what is entered will be at an odd position :)
word = input("Type: ")
word = list(word)
print(word)
odd_letters = ''
even_letters = ''
length = int(len(word))
for i in range(1,length+1):
if i%2 == 0:
even_letters = even_letters + word[i-1]
else:
odd_letters = odd_letters + word[i-1]
print("even_letters",even_letters)
print("odd_letters",odd_letters)
word=input()
word_num=len(word)
print(word_num)
odd_num=[]
even_num=[]
for letters in range(0,word_num,2):
odd_num.append(word[letters])
for letters in range(1,word_num,2):
even_num.append(word[letters])
print(odd_num)
print(even_num)
This is the answer it works with every word, and follows all the requirements.

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