簡體   English   中英

如何用多個字符串替換子字符串

[英]How to replace a substring with multiple strings

我正在設置一個圖形計算器,需要從多個給定的x值中計算出y值的列表。 例如,等式為10x + 5。 我將視圖窗口設置為-10到10。我需要找到一種方法來計算10(-10)+5,一直到10(10)+5。

為此,我需要找到一種用整數列表替換x的方法。 我該如何實現?

replace()不起作用,因為它僅接受str而不接受列表。

equation.replace('x', xValues)

[equation.replace('x', y) for y in xValues]使用列表理解

您可以簡單地將replace函數應用於您感興趣的值列表:

xValues = range(-10, 11)
equation = "10*x+5"
result = [equation.replace("x", str(v)) for v in xValues]

請注意,replace使用兩個字符串參數,因此您需要先將替換值轉換為字符串。

上面將為您提供所有表達式的列表:

['10*-10+5',
 '10*-9+5',
 '10*-8+5',
 '10*-7+5',
 '10*-6+5',
 '10*-5+5',
 '10*-4+5',
 '10*-3+5',
 '10*-2+5',
 '10*-1+5',
 '10*0+5',
 '10*1+5',
 '10*2+5',
 '10*3+5',
 '10*4+5',
 '10*5+5',
 '10*6+5',
 '10*7+5',
 '10*8+5',
 '10*9+5',
 '10*10+5']

遍歷值:

for x in range(-10, 11):
  print(10*x + 5)

您可以使用簡單的for循環

for i in range(-10,11): #upper limit is 11 because it exclude it and run till 10
    print((10*i)+5)     #if you want answer only
    print("10 * "+str(i)+" + 5") #if you want equation
    print("10 * "+str(i)+" + 5",(10*i)+5) #if you want both equation with answer

使用前刪除評論

暫無
暫無

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

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