[英]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?我知道my_str[1::3]
以 3 个块的形式获取每个第二个字符,但是如果我想获取每个第二个和第三个字符怎么办? 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.我认为使用带有enumerate
的列表理解将是最干净的。
>>> "".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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.