簡體   English   中英

在Python中使用函數返回子字符串

[英]Using a function in Python to return a substring

我感覺我的問題很基礎,因為我是計算機科學系的第一學期學生。

我被要求返回類似於"abcd5efgh" 的字符串中的數字之前形成子字符串 想法是使用一個函數給我"abcd" 我想我需要使用.isdigit ,但是我不確定如何將其轉換為函數。 先感謝您!

可以用regexp完成,但是如果您已經發現isdigit ,為什么在這種情況下不使用它呢?

如果找不到數字,則可以修改最后一個return s行以返回其他內容:

def string_before_digit(s):
    for i, c in enumerate(s):
        if c.isdigit():
            return s[:i]
    return s # no digit found

print(string_before_digit("abcd5efgh"))

我目前也是學生,這就是我要解決的問題的方式:*對於我的學校,我們不允許使用內置函數(如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")

希望這可以幫助

功能方法:)

>>> from itertools import compress, count, imap
>>> text = "abcd5efgh"
>>> text[:next(compress(count(), imap(str.isdigit, text)), len(text))]
'abcd'

下面的代碼將使用正則表達式為您提供第一個非數字部分。

import re
myPattern=re.compile('[a-zA-Z]*')
firstNonDigitPart=myPattern.match('abcd5efgh')
firstNonDigitPart.group()
>>> 'abcd'

如果您不被允許使用正則表達式,也許是因為他們告訴您手動進行正則表達式,則可以這樣進行:

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]

應該給您您想要的結果。

一個非常簡單的isdigit ,使用isdigit :)

>>> s = 'abcd5efgh'
>>> s[:[i for i, j in enumerate([_ for _ in s]) if j.isdigit()][0]]
'abcd'

itertools方法:

>>> from itertools import takewhile
>>> s="abcd5efgh"
>>> ''.join(takewhile(lambda x: not x.isdigit(), s))
'abcd'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM