python - 在 python 中浏览字符串

标签 python

请原谅这个极其琐碎/菜鸟的问题,至少它应该很容易回答。我一直在解决 coderbyte 问题并解决 python 中的简单问题,但遇到了困难。问题是,如果字符串(例如 d+==f+d++)的所有字母字符都被加号 (+) 包围,则返回 True,否则返回 false。我对有助于导航这些字符串的概念感到空白,我尝试使用循环和 if 语句进行操作,但它未能完全循环文本,并且始终返回 false(来自第一个问题):

def SimpleSymbols(str):
    split = list(str)
    rawletters = "abcdefghijklmnopqrstuvwxyz"
    letters = list(rawletters)

    for i in split:
        if i in letters and (((split.index(i)) - 1) == '+') and (((split.index(i)) + 1) == '+'):
            return True
        else:
            return False


print SimpleSymbols(raw_input())

还进行编辑以添加问题陈述:“使用 Python 语言,让函数 SimpleSymbols(str) 获取传递的 str 参数,并通过返回字符串 true 或 false 来确定它是否是可接受的序列。str 参数将由 + 和 = 符号组成,它们之间有几个字母(即++d+===+c++==a),并且要使字符串为真,每个字母必须被 + 符号包围。因此字符串到left 将为 false。字符串不会为空并且至少有一个字母。"

任何帮助将不胜感激。谢谢!

最佳答案

这是我如何完成第一部分(如果我不使用正则表达式):

import string

LOWERCASE = set(string.ascii_lowercase)

def plus_surrounds(s):
    """Return True if `+` surrounds a single ascii lowercase letter."""
    # initialize to 0 -- The first time through the loop is guaranteed not
    # to find anything, but it will initialize `idx1` and `idx2` for us.
    # We could actually make this more efficient by factoring out
    # the first 2 `find` operations (left as an exercise).
    idx2 = idx1 = 0

    # if the indices are negative, we hit the end of the string.
    while idx2 >= 0 and idx1 >= 0:
        # if they're 2 spaces apart, check the character between them
        # otherwise, keep going.   
        if (idx2 - idx1 == 2) and (s[idx1+1] in LOWERCASE):
            return True
        idx1 = s.find('+', idx2)
        idx2 = s.find('+', max(idx1+1, 0))
    return False

assert plus_surrounds('s+s+s')
assert plus_surrounds('+s+')
assert not plus_surrounds('+aa+')

我认为,如果您研究这段代码并理解它,您应该能够毫不费力地获得第二部分。

关于python - 在 python 中浏览字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870338/

相关文章:

python - 开区间(a,b)和半开区间(a,b]使用Python的linspace

python - Cython 中 C++ 函数的性能不佳

python - 如何从 Windows 命令提示符运行 Openscad

python - pandas 字符串在基于另一列的一列中出现的次数

Python:对于文件循环,如何在for循环中获取下一行?

python - 如何在 Pandas 中组合文本行

python - 将最长的字段放入数据框列

python - 有没有办法创建 Alexa 智能家居组并根据发现的设备以编程方式预先填充它?

python - 由于 channel 信息,灰色图像上的 ROS CvBridge 无法正常工作

python - 如何在Python中正确编码?