2011-10-05 10 views
5

小文字の文字列を入力して対応する2文字の文字列を入力するように求めるPythonプログラムを作成します。 2桁のコード。たとえば、入力が「home」の場合、出力は「08151305」になります。数字が10未満の場合はリストの数字の前に0をつけます(Pythonで)

現在、私は、すべての番号のリストを作成するために取り組んで私のコードを持っているが、私は それが1桁の数の前に0を追加することができません。

def word(): 
    output = [] 
    input = raw_input("please enter a string of lowercase characters: ") 
    for character in input: 
     number = ord(character) - 96 
     output.append(number) 
    print output 

これは私が得る出力されます:私はそれを行う方法がわからない、私はこれを行うには、文字列または整数にリストを変更する必要があるかもしれないと思うけど

word() 
please enter a string of lowercase characters: abcdefghijklmnopqrstuvwxyz 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] 

+0

が賢明だろう 'STRING'に' list'から 'output'を変更します。これは '[]'の代わりに '' ''で '.append()'の代わりに '+ ='を使って初期化するのと同じくらい簡単です。 – Johnsyweb

答えて

11

output.append("%02d" % number)とする必要があります。これはPython string formatting operationsを使用して左のゼロ埋め込みを行います。

+0

ありがとう!完全にはたらきました – JR34

4
output = ["%02d" % n for n in output] 
print output 
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26'] 

Pythonは多くのCと他の言語のsprintfように動作し、操作[docs]の書式文字列を有しています。あなたはあなたのデータだけでなく、あなたのデータを望むフォーマットを表す文字列を与えます。私たちの場合、書式文字列("%02d")は、0 - 2文字(02)まで埋め込まれた整数(%d)を表しています。

あなただけの数字と他には何を表示したい場合は、文字列を使用することができます.join()単純な文字列を作成するには、[docs]方法:

print " ".join(output) 
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 
10

または、使用をこれを行うように設計された組み込み関数 - zfill()

def word(): 
    # could just use a str, no need for a list: 
    output = "" 
    input = raw_input("please enter a string of lowercase characters: ").strip() 
    for character in input: 
        number = ord(character) - 96 
     # and just append the character code to the output string: 
        output += str(number).zfill(2) 
    # print output 
    return output 


print word() 
please enter a string of lowercase characters: home 
08151305 
+0

+1についてはzfillメソッドに言及してください – Jetse

4

Python標準ライブラリdocs 2.7によると、%フォーマット操作を使ってPython 3をリリースした後、注意が必要です。 Here's the docs on string methods; str.formatをご覧ください。

"新しい方法" である:

output.append("{:02}".format(number)) 
+1

1つのオブジェクトを変換する場合は、単純に "'、' .join(入力でcの場合はformat(ord(c) - 96、 '02')を使用する方が簡単です。 – eryksun

+0

この問題のためにstr.formatを推薦するためのupvote。 –

関連する問題