【问题标题】:Get every 2nd and 3rd characters of a string in Python在Python中获取字符串的每第二个和第三个字符
【发布时间】:2022-01-10 16:29:13
【问题描述】:

我知道my_str[1::3] 会以 3 个为一组来获取每个第二个字符,但是如果我想获取每个第二个和第三个字符怎么办?有没有一种巧妙的方法可以通过切片来做到这一点,或者我是否需要一些其他方法,比如列表理解和连接:

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

【问题讨论】:

  • 请提供输入输出示例

标签: python string slice


【解决方案1】:

我认为使用enumerate 的列表理解将是最干净的。

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

【讨论】:

    【解决方案2】:

    为什么不过滤掉第一个项目,而不是只得到第 2 和第 3 个字符?

    类似这样的:

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

    【讨论】:

      猜你喜欢
      • 2022-08-23
      • 2021-04-09
      • 2018-03-12
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      相关资源
      最近更新 更多