【问题标题】:Distance between consecutive occurrences of a character字符连续出现之间的距离
【发布时间】:2021-04-09 13:09:13
【问题描述】:

我需要编写一个程序来确定给定字符的连续出现之间的空格长度。如果出现是相邻的,它们之间的空间被认为是1。

我只能在两个符号之间计算

text = input ('enter text')
find = input ('enter a search character')
x = text.find(find)

y = text.rfind(find)
   
dist = text.rfind(find) - text.find(find)
print(dist)

【问题讨论】:

  • 你的问题是什么?
  • 示例输出会很好。
  • str.find() 也接受一个起始索引参数。你可以利用它。 docs.python.org/3/library/stdtypes.html#str.find
  • 示例结果给出了前两个字符之间的距离,但是接下来的字符呢?
  • 它实际上给出了搜索字符的第一个和最后一个实例之间的距离。

标签: python find-occurrences


【解决方案1】:

此代码将将距离输出到列表中

text = "Maybe it's in the gutter, where I left my lover. What an expensive fate."
find = input('Enter a search character')

spaces_list = [len(x) + 1 for x in text.split(find)[1:-1]]
print(spaces_list)

输出

>>> Enter a search character
>>> t

>>> [7, 6, 1, 16, 15, 17]

【讨论】:

  • 谢谢,我就是这个意思
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多