Python newspace persists
我正在尝试创建一个名称生成器:
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 27 28 29 30 31 32 33 34 35 36 37 38 | from random import randint relation = { 'A' : ['B', 'C', 'D', 'F', 'R', 'Y'], 'B' : ['E', 'O', 'I'], 'C' : ['A', 'E', 'H', 'R', 'O', 'I'], 'D' : ['A', 'E', 'H', 'R', 'O', 'I'], 'E' : ['R', 'T', 'P', 'S', 'F', 'L', 'X'], 'F' : ['E', 'U', 'I', 'O', 'A'], 'G' : ['R', 'O', 'A'], 'H' : ['E', 'I', 'O', 'A'], 'I' : ['N', 'X', 'S', 'E', 'T', 'P', 'L', 'M'], 'J' : ['A', 'I', 'O', 'Y'], 'K' : ['I', 'E', 'A'], 'L' : ['I', 'E'], 'M' : ['O', 'Y', 'I'], 'N' : ['E', 'I', 'O', 'A'], 'O' : ['V', 'T', 'N'], 'P' : ['I', 'A', 'E', 'O'], 'Q' : ['U', 'E', 'I'], 'R' : ['E', 'I', 'A'], 'S' : ['T', 'I', 'O', 'A', 'H'], 'T' : ['H', 'E', 'I'], 'U' : ['B', 'G', 'L'], 'V' : ['E', 'U', 'I', 'A'], 'X' : ['I', 'O'], 'Y' : ['E', 'L'], 'Z' : ['O', 'I'] } char = (raw_input("Enter an English alphabet:")).upper() letters = int(raw_input("How many letters:")) for i in range(0, letters): if i==0: print char, else: print char.lower(), char = (relation[char])[randint(0, len(relation[char])-1)] print '' raw_input("Press [ENTER] to exit...") |
但问题是打印名称时有一个空格。
例如:
Enter an English alphabet: T
How many letters: 5
T i p a y
Press [ENTER] to exit...
如何删除空格?
P.S:我是初学者:)
我不太确定你打印的推理理由,但是你可以有一个单词变量,然后将你想出的所有
1 2 3 4 5 6 | word = '' for i in range(0, letters): word += char char = (relation[char])[randint(0, len(relation[char])-1)] print word.lower().capitalize() print '' |
基于
1 2 3 4 5 6 | charList = [] for i in range(0, letters): charList.append(char) char = (relation[char])[randint(0, len(relation[char])-1)] print ''.join(charList).lower().capitalize() print '' |
这是引起这种情况的逗号。 用逗号分隔的
1 | print"a","b" |
打印
1 | print"a", |
打印
1 | print"a" |
打印
但是,您可以更改代码以使用变量:
1 2 3 4 5 6 7 8 9 | name = '' for i in range(0, letters): if i==0: name += char else: name += char.lower() char = (relation[char])[randint(0, len(relation[char])-1)] print name print '' |
或更短更有效:
1 2 3 4 5 6 7 | letter_list = [] for i in range(0, letters): letter_list.append(char) char = (relation[char])[randint(0, len(relation[char])-1)] name = ''.join(letter_list) print name.lower().capitalize() print '' |