Reputation: 11
I am writing some code to see print out a list of words that I can make with the string of letters 'myLetters', but for some reason my formatting wont work. It is supposed to come out as a list of words with as many spaces between it and the value as the length of myLetters + 4
def scrabbleWords(myLetters):
letterPoints = {'a':1,'b':3,'c':3,'d':2, 'e':1,'f':4,'g':2,'h':4,\
'i':1,'j':8,'k':5,'l':1,'m':3,'n':1,'o':1,'p':3,'q':10,'r':1,'s':1,\
't':1,'u':1,'v':4,'w':4,'x':8,'y':4}
wordList = createWordList('wordlist.txt')
myWords = []
for myWord in wordList:
x = canWeMakeIt(myWord,myLetters)
if x == True:
myWords.append(myWord)
pointWordList = []
for myWord in myWords:
t = getWordPoints(myWord,letterPoints)
pointWordList.append((t,myWord))
pointWordList.sort(reverse=True)
lenx = str(len(myLetters)+4)
for pointValue, myWord in pointWordList:
x = '{:'+lenx+'}{}'.format(myWord,pointValue)
print(x)
Upvotes: 1
Views: 4938
Reputation: 123501
The problem is with the '{:'+lenx+'}{}'.format(myWord,pointValue)
expression which tries to add lenx+'}{}'.format(myWord,pointValue)
to the sum '{:'+lenx
.
This would do what I think you want and be a little more readable in my opinion:
x = '{:{width}}{}'.format(myWord, pointValue, width=lenx)
EDIT: Plus this works whether lenx
is an integer or string value.
Upvotes: 3
Reputation: 176
The "Single '}' encountered in format string" error is due to the fact that we are looking at a bit of code that does not work without some bracketing.
You wrote
'{:'+lenx+'}{}'.format(myWord,pointValue)
but probably meant
('{:'+lenx+'}{}').format(myWord,pointValue)
whereas python's interpretation is:
'{:'+lenx+('}{}'.format(myWord,pointValue))
Upvotes: 0
Reputation: 213015
'{:'+lenx+'}{}'.format(myWord,pointValue)
interprets as
'{:' + lenx + '}{}'.format(myWord,pointValue)
Change it to:
'{1:{0}}{2}'.format(lenx, myWord, pointValue)
EDIT: don't forget to change lenx
to an integer (or don't convert it to string at all):
lenx = len(myLetters) + 4
Upvotes: 4