Home > database >  Get every 2nd and 3rd characters of a string in Python
Get every 2nd and 3rd characters of a string in Python

Time:01-11

I know that my_str[1::3] gets me every 2nd character in chunks of 3, but what if I want to get every 2nd and 3rd character? Is there a neat way to do that with slicing, or do I need some other method like a list comprehension plus a join:

new_str = ''.join([s[i * 3   1: i * 3   3] for i in range(len(s) // 3)])

CodePudding user response:

I think using a list comprehension with enumerate would be the cleanest.

>>> "".join(c if i % 3 in (1,2) else "" for (i, c) in enumerate("peasoup booze scaffold john"))
'eaou boz safol jhn'

CodePudding user response:

Instead of getting only 2nd and 3rd characters, why not filter out the 1st items?

Something like this:

>>> str = '123456789'
>>> tmp = list(str)
>>> del tmp[::3]
>>> new_str = ''.join(tmp)
>>> new_str
'235689'
  •  Tags:  
  • Related