Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line.
Sample Input:
2
Hacker
Rank
Sample Output:
Hce akr
Rn ak
One way to complete this problem is to loop through the indeces (length of the string), check if it’s an even or an odd index, and concatenate it with the corresponding string. A sample solution is outlined below using this method.
def even_odd(S):
even_ind = "" #create a storage for even indeces
odd_ind = "" #create a storage for odd indeces
for i in range(len(S)): #from 0 up to length of the string
if(i % 2 == 0): #check if an even index
even_ind += S[i] #concatenate the character of the index with even_ind
else: #else if an odd index
odd_ind += S[i] #concatenate the character of the index with odd_ind
print("{even} {odd}".format(even = even_ind, odd = odd_ind)) #print each, separated by a space
N = int(input()) #take in how many strings they will input
for i in range(N):
user_str = input() #take string input from the user
even_odd(user_str) #call the function for the string inputted
Instead of making a for loop to loop through the indeces one at a time, you can use the my_string[start:stop:by] indexing.
#using string[start:stop], the "by" defaults to 1
s1 = "Hello"
s1[1:3]
#using string[start:stop:by]
s2 = "Hello World"
#print all even indeces from the beginning to end of the string
#(len(s2) = 11 so index 10 "d" would be printed)
s2[0:len(s2):2]
#when start is left blank it defaults to 0
#when end is left blank it defaults to the length of the string - 27
s3 = "Thanks for reading my blog!"
s3[::2]
#take odd indeces only
s3[1::2] #start from 1 through the end of the string
el #from index 1 (e) UP TO index 3 (l)
HloWrd #from index 0 (H) through last index 10 (d)
Tak o edn ybo! #from index 0 (T) through last even index 26 (!)
hnsfrraigm lg #from index 1 "h" through the last odd index 25 (g)
With this concept, we could take a user string and print it’s even and odd indeces.
S = input()
print(S[::2], S[1::2])
To allow the user to enter multiple strings, loop through a user input.
def even_odd():
for N in range(int(input())):
S = input()
print(S[::2], S[1::2])
even_odd()
Sample Solution 1:
# Enter your code here. Read input from STDIN. Print output to STDOUT
def even_odd(s1):
even_ind = ""
odd_ind = ""
for i in range(len(s1)):
if(i % 2 == 0):
even_ind += s1[i]
else:
odd_ind += s1[i]
print("{even} {odd}".format(even = even_ind, odd = odd_ind))
num_strs = int(input())
for i in range(num_strs):
user_str = input()
even_odd(user_str)
Sample Solution 2:
# Enter your code here. Read input from STDIN. Print output to STDOUT
def even_odd():
for N in range(int(input())):
S = input()
print(S[::2], S[1::2])
even_odd()