Python 新空间持续存在

Python newspace persists

我正在尝试制作名称生成器:

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: 我是初学者:)

是逗号导致的。 print 以逗号分隔的语句加白 spaces:

print "a", "b"

打印 a b

print "a",

打印 (白色 space)

print "a"

打印 a(没有白色 space)

但是,您可以更改代码以使用变量:

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 ''

或更短更高效:

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 ''

我不太确定你打印的理由,但你可以有一个单词变量,然后将你想出的所有 char 附加到单词变量上,然后在结尾。这不会在字母

之间有空格
word = ''
for i in range(0, letters):
    word += char
    char = (relation[char])[randint(0, len(relation[char])-1)]
print word.lower().capitalize()
print ''

根据PM 2 Rings的建议你也可以这样做:

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 ''