【问题标题】:How to get the first letter index of a string after spaces in Python? [duplicate]如何在Python中获取空格后的字符串的第一个字母索引? [复制]
【发布时间】:2022-01-24 11:15:55
【问题描述】:

有没有办法在n 空格数之后获取字符串的第一个字母索引?

我知道用for loop 很容易制作,但为了简单起见,有没有更简洁的方法?

string_1 = "    Hello" # Return 4
string_2 = "        Bye" # Return 8

【问题讨论】:

    标签: python string


    【解决方案1】:

    方法strip()在第一个字符之前和最后一个字符之后剪切空格(以及多个内部,如x y

    所以:

    x = '  abc'
    x = x.strip()
    print(x)      # result -> 'abc'
    

    【讨论】:

    • 这不是所要求的……
    • 有很大的机会,那就是:this is not what you are looking for, but exactly what you need 那种情况:)
    • 那么应要求提供更多详细信息或对此进行评论
    • 我没想到。感谢您的提示,我以后会尝试这样做。
    【解决方案2】:

    您可以使用filterenumeratenext在满足条件时停止:

    string_1 = "    Hello"
    
    next(filter(lambda x: x[1]!=' ', enumerate(string_1)))[0]
    # 4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-05
      • 2017-09-05
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2017-05-06
      • 2021-06-15
      相关资源
      最近更新 更多