【问题标题】:How can I find the position of a character in a string? [Python] [duplicate]如何在字符串中找到字符的位置? [Python] [重复]
【发布时间】:2021-05-24 23:37:22
【问题描述】:

我有这个字符串:"----d---"

如何在 Python 中找到“d”的位置?

我想要这个输出:

Position: 5

【问题讨论】:

  • print("----d---".index("d")+1),加一,因为python的索引从0开始

标签: python loops


【解决方案1】:

改进的答案:

def get_position(s: str, c: str):
    return s.index(c)

print("Position:", get_position("----d---", "d"))

上一个更基本的答案:

def get_position(s: str, c: str):
    for i, char in enumerate(s):
        if char == c:
            return i


print("Position:", get_position(s="----d---", c="d"))

【讨论】:

  • 我喜欢这种方法。我要做的唯一更改是使用改进的答案创建一个函数:def find_index(s, c): return("Position:", s.index(c)+1)
  • 将您的建议纳入我的回答中。
【解决方案2】:

使用 rindex:

jeff = "wow bru"
print("Position:",jeff.rindex("r")+1)

解释:

jeff.rindex("r") 返回分配给jeff 的字符串中字母 r 的索引,+1 只是将该值增加一,因为索引从 0 开始,我们希望它从 1 开始。

【讨论】:

    猜你喜欢
    • 2015-06-26
    • 2011-01-23
    • 1970-01-01
    • 2015-07-25
    • 2014-10-07
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多