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