Combining two strings to form a new string - 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.

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

how to detect a string in a variable

x = input("enter input: ")
if x == "hello":
print ("it does")
How would I detect if x has hello stored even if it has other charaters/strings?
This is as simple as using the in keyword.
x = "123hellomore"
if "hello" in x:
print("Hi there")
This only detects hello, if it is unobstructed so still in one word (not like "**hel*lo")
If entered input is single string then x below will be array of one element, if entered input is space separated strings (string of strings) then x will be array of multiple strings, below code handles both options
x = input("Enter input: ").split()
for y in x:
if y=="hello"
print("it does")

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

Where is issue with final display in this code?

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

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'

Resources