(Pythonで)初級クラス複数の行に文字列を出力する
私は自宅でedxコースを利用してプログラミングを進めています。私が打ち込んだ課題の1つに、私は困惑しています。目標は、整数を挿入してtimesテーブルを出力できるようにすることです。
この表は、列と行に分割されます。私は、必要な値を、可変の入力が与えられたときのすべての数の文字列に組み立てることができます。私は整数の間に呼び出されるタブを追加しました。
これは1つの文字列であり、最初に入力したさまざまな値に基づいてさまざまな大きさの隙間に入り、印刷することはできません。
テキストの折り返しを試しましたが、別の例に基づいてどのように配置してもエラーは発生しました。
解決策を見つけて、なぜそれが機能するのかを説明してください。私はこの問題を解決するスパンコーディングされたコードラインを持っていないが、私にはまだ無知なままにしておくことを学ぶことを試みている。
このクラスのスラックで見つかったヒントのうち、これまでにコースに掲載されている用語やコマンドはありませんでした。しかし、リストされていない多く。
これは私が持っているものであり、別の解決策を試して残ったエクストラを無視してください。
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])
"\ t"ではなく "\ n"を使用して、タブではなく新しい行を取得することができます。しかし、あなたが与えられたヒントから、行を個別に印刷すること、つまり行ごとに別々の文字列を作成して印刷することが期待されるように見えます。 – RuthC
ありがとうございます。はい、文字列を異なるサイズのセクションに分割して初期変数と一致させ、それを印刷して私に合うようにする方法です。 – rmcrow2