在python中浏览一个字符串

时间:2014-02-19 03:19:56

标签: python

请原谅这个令人难以置信的微不足道的小问题,至少它应该很容易回答。我一直在解决coderbyte问题并解决python中的简单问题,但是遇到了问题。如果一个字符串(例如d + == f + d ++)的所有字母字符都被加号(+)包围,并且如果不返回false,则问题是返回True。我正在理清这个有助于浏览这些字符串的概念,我尝试使用循环和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),对于字符串为true,每个字母必须用+符号包围。所以字符串到left将是false。字符串不会为空,并且至少有一个字母。“

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

以下是我将如何处理第一部分(如果我没有使用正则表达式):

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+')

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

答案 1 :(得分:0)

更多的注释而不是答案,但我想提一下正则表达式作为解决方案,不是因为它适合你的场景(这看起来很明显是家庭作业 - 所以我明白你几乎肯定不允许使用正则表达式)但是只是想早点在Python中,几乎所有的事情都由import foo解决。

import re

def SimpleSymbols(target):
    return not (re.search(r"[^a-zA-Z+=]",target) and re.search(r"(?<!\+)\w|\w(?!\+)",target))