[英]How to add one to each digit?
這是作業:
編寫一個以字符串形式傳遞的函數,並返回一個與原始字符相同的新字符串,不同之處在於所有數字均由高1的數字代替。 9替換為0。
這是我到目前為止的內容:
number = ""
s = str(number)
l = []
def increase_digit(text):
for num in s:
num = int(num)
num += 1
if num > 9:
num = 0
l.append(num)
else:
l.append(num)
您目前的做法是縮進錯誤,但根本不檢查數字和增量。
相反,您可以遍歷字符串並將數字遞增1。 如果僅從增量中獲取最后一位數字,則可以根據需要將'10'
轉換為'0'
:
def increase_digit(text):
return ''.join(str(int(c)+1)[-1] if c.isdigit() else c for c in text)
例子:
increase_digit('1ab2')
# '2ab3'
increase_digit('56789')
# '67890'
increase_digit('abcde')
# 'abcde'
您可以嘗試如下操作:
a = ['1ab2', '56789', 'abcde']
a2 = [''.join([chr(ord(c)+1) if c.isdigit() else c for c in b ]).replace(':','0') for b in a]
print a2
輸出:
['2ab3', '67890', 'abcde']
在將其強制轉換為整數之前,應檢查num是否為數字。
這是我的代碼和輸出
def increase_digit(text):
l = []
for num in text:
if num.isdigit():
num = int(num)
num += 1
if num > 9:
num = 0
l.append(str(num))
return l
print(increase_digit('1ab2'))
print(increase_digit('56789'))
print(increase_digit('abcde'))
我的代碼輸出是這樣的:
['2', 'a', 'b', '3']
['6', '7', '8', '9', '0']
['a', 'b', 'c', 'd', 'e']
你快到了 您忘記了幾件事:
num
是否為數字( num.isdigit()
)。 num
為字符串形式。 這是此問題所需的更改:
def increase_digit(text):
l = []
for num in text:
if num.isdigit(): # issue 1
num = int(num) + 1
if num > 9:
num = 0
num = str(num) # issue 2
l.append(num)
return ''.join(l) # issue 3
9 + 1 = 10
。 多數民眾贊成在9
以上的唯一情況,並且可以通過取數字的最后一位數字0
來無條件解決,所以
if num > 9:
num = 0
num = str(num)
進入str(num)[-1]
。 我們可以繼續消除多行條件-
num = int(num) + 1
num = str(num)[-1]
如num = str(int(num) + 1)[-1]
,現在我們有一個小循環-
for num in text:
if num.isdigit():
num = str(int(num) + 1)[-1]
l.append(num)
可以轉化為列表理解(對於for
)和三元if-else
條件-
l = [str(int(num) + 1)[-1] if num.isdigit() else num for num in text]
然后,結合最終回報,我們得到
def increase_digit (text):
return ''.join(str(int(x) + 1)[-1] if x.isdigit() else x for x in text)
您可以繼續使用這種替換方法,並使用string.digits
, str.translate
等使代碼更優雅-但我相信這個水平足以完成作業。
發生是因為您要增加9,然后才比較“ num> 9”?
這還是輸出還是所需的輸出?
"increase_digit('1ab2') → '2ab3'
increase_digit('56789') → '67890'
increase_digit('abcde') → 'abcde'"
這樣的旋轉是使用模運算符%
的典型示例:
def increase_digit(text):
return ''.join(str((int(c)+1) % 10) if c.isdigit() else c for c in text)
我不完全了解您的代碼,但您似乎正在嘗試執行以下操作:
''.join([str((int(s)+1) % 10) if s.isdigit() else s for s in inp])
糟糕,它們看起來確實很相似;-) @Chris_Rands嗨
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.