TaxpayersMoney
TaxpayersMoney

Reputation: 689

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

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

Upvotes: 0

Views: 870

Answers (2)

Ron Zano
Ron Zano

Reputation: 590

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'

Upvotes: 1

AKX
AKX

Reputation: 169407

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'

Upvotes: 2

Related Questions