简体   繁体   中英

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

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'

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM