0

I have a string:

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

I need to print the strings with the characters present at odd and even position in the above string.

For example:

  • for odd position, output should be:

    'ACEGIKMOQSUWY'
    
  • for even position, output should be

    'BDFHJLNPRTVXZ'
    
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • Possible duplicate of [Python program to split a list into two lists with alternating elements](https://stackoverflow.com/questions/1442782/python-program-to-split-a-list-into-two-lists-with-alternating-elements) – Aran-Fey Mar 29 '18 at 19:18

1 Answers1

10

You need to use string slicing. For example:

>>> my_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# For odd
>>> my_str[::2]
'ACEGIKMOQSUWY'

# For even
>>> my_str[1::2]
'BDFHJLNPRTVXZ'

General syntax of string slicing is string[start:end:jump] where:

  • start: is the starting index for slicing the string. Empty value means start of the string i.e. index 0

  • end: is the index till which you want to slice the string. Empty value means end of the string

  • jump: is used to jump the elements from start such that you'll get values in the order start, start+jump, start+2*jump, so on till your string reaches end. Empty value means 1

Georgy
  • 12,464
  • 7
  • 65
  • 73
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126