python - How to use len() to create an equal-length string full of asterisks? -


my assignment create game of hangman. i'm trying turn "someword" "********" display player, code returns 1 asterisk many given input.

the following text file i'm reading words from:

python different 

(it continues many lines)

here's code:

import random  def diction(random):      lives = 5     dictionary = {"secretword" : random, "lives" : lives}     guess = len(dictionary["secretword"]) * "*"     print (dictionary["secretword"])     print (guess)   file = input("please insert file name: ")  f = open(file) content = f.readlines() f.close()  random = (random.choice(content)) random = random.replace(" ", "")   diction(random) 

i'm expecting output of (for example)

python ****** 

and instead getting output of

python ******* 

the problem here file.readlines leaves trailing newline character, file like

foo bar spam eggs 

becomes

['foo\n','bar\n','spam\n','eggs\n'] 

the solution use str.strip (or str.rstrip if anticipate having leading whitespace) on each element. instance:

words = map(str.strip, some_file.readlines()) # in python3, should call list(map(str.strip, some_file.readlines())) secret_word = random.choice(words) 

or else strip word need , ignore rest.

words = some_file.readlines() secret_word = random.choice(words).strip() 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -