1

私は最初の学期のコンピューター サイエンスの学生なので、私の質問はかなり基本的なものだと感じています。

のような文字列の数字の前に形成された部分文字列を返すように求められました"abcd5efgh"。アイデアは、関数を使用して私に与えることです"abcd"。を使用する必要があると思います.isdigitが、関数に変換する方法がわかりません。前もって感謝します!

4

7 に答える 7

1

私は現在学生でもあり、これが私がこの問題にアプローチする方法です:*私の学校では、Pythonでそのような組み込み関数を使用することは許可されていません:/

     def parse(string):
       newstring = ""
       for i in string:
          if i >= "0" and i <= "9":
             break
          else:
             newstring += i
       print newstring #Can use return if your needing it in another function

     parse("abcd5efgh")

お役に立てれば

于 2013-04-16T12:58:55.590 に答える
1

機能的なアプローチ:)

>>> from itertools import compress, count, imap
>>> text = "abcd5efgh"
>>> text[:next(compress(count(), imap(str.isdigit, text)), len(text))]
'abcd'
于 2013-04-16T13:03:07.753 に答える
0

正規表現の使用が許可されていない場合は、手動で明示的に行うように指示された可能性があるため、次のようにすることができます。

def digit_index(s):
    """Helper function."""
    # next(..., -1) asks the given iterator for the next value and returns -1 if there is none.
    # This iterator gives the index n of the first "true-giving" element of the asked generator expression. True-giving is any character which is a digit.
    return next(
        (n for n, i in enumerate(i.isdigit() for i in "abc123") if i),
        -1)

def before_digit(s):
    di = digit_index(s)
    if di == -1: return s
    return s[:di]

あなたの望む結果が得られるはずです。

于 2013-04-16T12:56:29.857 に答える