[英]My flag isnt catching, it only returns the first possible. Im trying to take a string and add a D after it if its a digit and a X if it isnt
def inBetweenAdv(var1): #this is the input
total = ""
isit = False # my flag
for i in var1:
if (i.isdigit): #trying to see if i is a digit or not
isit = True
if isit:
total = total + str(i) + "D"
if isit == False:
total = total +str(i) + "X"
return total
如果你使用 isdigit() 你會得到一個錯誤,因為 int 和 float 沒有 isdigit() 方法,除非你想驗證像“3”這樣的東西,但是不需要將 i 轉換為字符串。 您正在嘗試放置一個標志,但這些方法可以像標志一樣使用,例如,如果 i.isdigit() 將返回 True 與 isinstance 相同,如果 i 是 int 或 float 句子將評估 True 或 False。
def inBetweenAdv(var1):
total = ""
for i in var1:
if isinstance(i, int) or isinstance(i, float):
total = total + str(i) + "D"
else:
total = total +str(i) + "X"
return total
我想這就是你想要做的。 但是我不確定您是否想要返回一個包含所有值的字符串,我猜您想要返回一個列表。 在這種情況下是:
def inBetweenAdv(var1):
lst = []
for i in var1:
if isinstance(i, int) or isinstance(i, float):
lst.append(str(i) + "D")
else:
lst.append(str(i) + "X")
return lst
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.