python中Beginning classes在多行上打印字符串
我在家採取edx課程將我的技能集擴展到編程中。我遇到的其中一項任務讓我難住。目標是能夠插入一個整數併爲其打印一個時間表。
該表將被分解爲列和行。我可以將所需的值組合成一個字符串,用於給定變量輸入的所有數字。我添加了在整數之間調用的選項卡。
現在這是一個字符串,我不能讓它打破到不同大小的chinks和基於最初輸入的不同值打印。
我試過文本打包,但無論如何我都把它放在不同的例子基礎上。
請幫我找到一個解決方案,並解釋其原因。我正試圖學習這一點,沒有一個可以解決問題的勺子代碼,但仍然讓我無法理解。
我在這門課的鬆懈中找到的提示都沒有包含到目前爲止課程中列出的術語或命令。很多沒有列出的。
下面是我所擁有的,請忽略嘗試不同解決方案時留下的額外費用。
mystery_int = 5
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#This is a tough one! Stick with it, you can do it!
#
#Write a program that will print the times table for the
#value given by mystery_int. The times table should print a
#two-column table of the products of every combination of
#two numbers from 1 through mystery_int. Separate consecutive
#numbers with either spaces or tabs, whichever you prefer.
#
#For example, if mystery_int is 5, this could print:
#
#1 2 3 4 5
#2 4 6 8 10
#3 6 9 12 15
#4 8 12 16 20
#5 10 15 20 25
#
#To do this, you'll want to use two nested for loops; the
#first one will print rows, and the second will print columns
#within each row.
#
#Hint: How can you print the numbers across the row without
#starting a new line each time? With what you know now, you
#could build the string for the row, but only print it once
#you've finished the row. There are other ways, but that's
#how to do it using only what we've covered so far.
#
#Hint 2: To insert a tab into a string, use the character
#sequence "\t". For example, "1\t2" will print as "1 2".
#
#Hint 3: Need to just start a new line without printing
#anything else? Just call print() with no arguments in the
#parentheses.
#
#Hint 4: If you're stuck, try first just printing out all
#the products in one flat list, each on its own line. Once
#that's working, then worry about how to organize it into
#a table.
#Add your code here!
import textwrap
a = mystery_int
b = 1
c = 0
d = 1
e = ""
f = ""
g = ""
h = "\t"
j = 1
k = a*2
for b in range(1,a + 1):
for c in range(1,a+1):
d = b * c
e +=str(d)+","
f = str(e)
g = str.replace(f,"," ,"\t")
#textwrap.wrap(g,10)
#print(g[0:int(k)])
print(g[:k])
您可以使用「\ n」而不是「\ t」來獲取新行而不是製表符。但是,從提示中可以看出,他們希望單獨打印這些行,即爲每行打印和打印一個單獨的字符串。 – RuthC
謝謝。是的,它是如何將字符串分解成不同大小的部分以匹配初始變量,並以這種方式打印它們,以便讓我適合。 – rmcrow2