I'm working on a simple python game in which the player attempts to guess letters contained in a word. The problem is, when I print a word, it's printing the \n at the end.
It looks like I need to use .strip to remove it. However, when I use it as seen in the following code, I get an attribute error saying that the list object has no attribute "strip".
Sorry for the newbie question.
import random
with open('wordlist.txt') as wordList:
secretWord = random.sample(wordList.readlines(), 1).strip()
print (secretWord)
Well, that's because lists don't have an attribute named strip. If you try print secretWord you'll notice that it's a list (of length 1), not a string. You need to access the string contained in that list, rather than the list itself.
secretWord = random.sample(wordList.readlines(), 1)[0].strip()
Of course, this would be much easier/cleaner if you used choice instead of sample, since you're only grabbing one word:
secretWord = random.choice(wordList.readlines()).strip()
Right. Strings in Python are not lists -- you have to convert between the two (though they often behave similarly).
If you'd like to turn a list of string into a string, you can join on the empty string:
x = ''.join(list_of_strings)
x is now a string. You'll have to do something similar to get from what you got out of random.sample (a list) to a string.
print adds a newline. You need to use something lower level, like os.write
random.sample() will return a list, it looks like you are trying to randomly select a single element from the list so you should use random.choice() instead:
import random
with open('wordlist.txt') as wordList:
secretWord = random.choice(wordList.readlines()).strip()
print (secretWord)
Related
I'm trying to code hangman for a class project, and I'm sure there are easier ways, but I can't make it look too advanced because I'm still a beginner. I'm trying to break down a word then put it into a list using ljust to make the word big enough to fit in the list, but then I need to remove the spaces from the list and I have no clue how.
It is not clear what you are asking. However, it seems like you want to turn a phrase into a list of characters. The following will turn a string into a list of characters after removing white spaces.
answer = "guess this"
answer = answer.ljust(15)
print(answer)
answer = answer.replace(" ", "") # remove spaces
print(answer)
characters = list(answer)
print(characters)
You don't need to change the list size in python. You can add to this list or remove from this list and python will handle the size change.
quote=input("Enter a quote ")
split=quote.split(quote)
for count in range(0,(split)+1):
print(split)
I've tried to do this but gave me the error:
for count in range(0,(split)+1):
TypeError: can only concatenate list (not "int") to list
You are receiving the error because your split variable is a list and you are adding + 1 (which is an integer) to the list which you cannot do in Python, hence a TypeError is thrown because the two types are not compatible with the + operator and Python doesn't know what to do.
Fixing the error
There are a few issues with the code that lead to that error being thrown and some minor logical issues:
You need to make sure you are splitting the string by spaces, not by the string itself.
You also need to get the length of the list of words in the string in your for loop.
In the loop you need to make sure you are outputting each word, not the whole list
See the code below for more details:
quote=input("Enter a quote ")
# Make sure to split by " " character
split=quote.split(" ")
# Make sure to get the length of the list of words in the split variable
for count in range(0, len(split)):
# Print each word, not the whole array
print(split[count])
Hope that helps ;)
print "YOU HAVE CHOSEN TO REARRANGE YOUR THE WORD THAT YOU ARE ABOUT TO ENTER..."
word = raw_input ("FIRSTLY YOU MUST ENTER A WORD TO BE REARRANGED, ENTER IT HERE:")
character_save = word[1]
def anagram(word):
if len(word)>1:
print str.replace('a','b')
word = str.replace(word[1],word[3])
word= str.replace(word[3], character_save,1)
print word
anagram(word)
I tried to fix this on numerous occasions, the problem with the first time was that it would just replicate characters instead of replacing the positions, the second time I tried to store the position that I was going to replace in a variable but now it mentions that I have only one argument given (when it should be 2).
Would it be easier to do this with a list instead of a string?
The replace message that you are using is called on the string that you want to replace and not on the str type itself.
In your case that is the word parameter that you are providing.
So if you replace the instances of str.replace with word.replace your code will run. However, it doesn't create an anagram yet. The algorithm is still lacking.
So i'm working on this really long program, and i want it to save an input inside of a new list, for that i have tried doing:
thing=list(input("say something")) #hello
print(thing)
#[h,e,l,l,o]
how can i arrange it to get [hello] instead?
Offhand, I'd say the easiest would be to initialize thing with an empty list and then append the user's input to it:
thing = []
thing.append(input("say something: "))
Use:
thing = [input("say something")]
In your version "hello" is treated as an iterable, which all Python strings are. A list then gets created with individual characters as items from that iterable (see docs on list()). If you want a list with the whole string as the only item, you have to do it using the square bracket syntax.
I am a beginner in python. I came across this question in codewars.
Jaden is known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example :
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
This is my attempt (I am supposed to code using a function)
def toJadenCase(string):
l = len(string)
for i in range(0,l):
if string[i] == ' ':
y = string[i]
string[i+1] = chr(int(y)-32)
return srting
s = raw_input()
print toJadenCase(s)
When run, the following errors showed up
How can mirrors be real if our eyes aren't real (this is the input string)
Traceback (most recent call last):
File "jaden_smith.py", line 9, in <module>
print toJadenCase(s)
File "jaden_smith.py", line 6, in toJadenCase
string[i+1] = chr(int(y)-32)
ValueError: invalid literal for int() with base 10: ''
I couldn't understand these errors even after google-ing it. Any help would be appreciated. I would also be great if other errors in my code are highlighted and a better code is suggested.
Thanks in advance :D
As Goodies points out, string should not be used as a variable name
Following the Zen of Python, this is technically a function that does exactly what you're trying to achieve:
def toJadenCase(quote):
return quote.title()
Edit:
Revised version to deal with apostrophes:
import string
def toJadenCase(quote):
return string.capwords(quote)
First you have to understand that strings are immutable, so you cannot set a single character inside a string, but build a new string from the old one and replace the old one (this can be usually done still in one pass so it's not a big complication).
Second, for most of these kind of operations, it is much better to use the methods of the string object itself, rather than redo everything from scratch.
Said that, there is still some complication with the question, but a function that does what you want is in the module string:
import string
s="How can mirrors be real if our eyes aren't real"
newstring=string.capwords(s)
If you prefer (why?!) a DIY solution (using string methods):
newstring=' '.join([ss.capitalize() for ss in s.split()])
Note that using split without argument splits the string on any whitespace (e.g. tabs etc.), that I think is the desired behavior.
If you want to do this without using a function that already exists, this is how I would do it and I'll explain everything:
Assuming you get a string with ONLY text based words and all words start with a character*
def toJadenCase(string):
words = string.strip().split()
# This first strips all empty spaces around the words in the text and then splits the string by spaces (default) otherwise you can add a character inside split in order to split it at the character. This returns a list of words in the sentence.
li = [] # initialize empty list
for word in words:
word = chr(ord(word[0])-32) + word[1:]
# So there's a couple of things going on here.
# I could use .upper() to upper case something (like word[0].upper() + word[1:]
# in order to get it but I wanted to do it without the use of that.
# That being said, ord just figures out the ascii number and subtracting
# 32 makes it uppercase. chr changes it back to a string.
# Then it can be concatenated to the rest of the word.
# Strings can be treated as lists in python so word[0] and word[1:] works
Also, word[1:] just means from the 1st index to the end.
li.append(word) # this appends the word to the list
return ' '.join(li) # this joins all of the words in the list with a space
Now, if you want something a lot more concise (you can use .capitalize()):
def toJadenCaseShort(string):
return ' '.join([x.capitalize() for x in string.strip().split()])
which returns:
>>> abc("hello my friends")
'Hello My Friends'
Basically what it does is it uses list comprehension to strip and then split the words, capitalizes them, and then joins them with spaces!
Of course, you could just use string.title() as mark s. says but what's the fun in that? :)
Here is the answer that passed for me
import string
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces