Skip to content
Advertisement

Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line

Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line.

Example:

s = adbecf => Print abc def

My approach:

t = input()
p = len(t)

for i in range(p):
  s = t[i]
  n = len(s)
  even = []
  odd = []
  for j in range(n):
    if j % 2 == 0:
      even.append(s[j])
  for j in range(n):
    if j % 2 != 0:
      odd.append(s[j])
  first_join=''.join(even)
  second_join = ''.join(odd)
  print("{} {}".format(first_join,second_join)

Advertisement

Answer

No need to use complex ways. here is a easy way to do it.

t = input()
p = len(t)
ans = "" # create empty string
for i in range(0,p,2):
    ans += t[i] # Add even characters
ans += " " # Add space.
for j in range(1,p,2):
    ans += t[j] # Add odd characters
print(ans)   

Input: adbecf

Output: abc def

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement