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.
Related
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 ;)
I was making a simple Hangman game in Python.
However, I have some problem in the following piece of code
newword=""
def update(word,guessword,ch):
for i in range(len(guessword)-1):
if ch==word[i]:
print(i)
if i==0:
newword=ch + guessword[1:]
else:
newword=guessword[0:i-1] + ch + guessword[i+1]
return newword
This update function is called when a match is found and is used to update guessword.
Here guessword is a string containing "_" for every unmatched position. The string word hold the original word. ch is the letter which is found in the original word.
Use range(len(guessword)):. The -1 is not needed, range already excludes the upper bound.
Use guessword[i+1:] at the end - you forgot the :. Otherwise it's just one character.
That should fix your existing code. To make it better, I suggest making guessword a list of characters so that you can modify it, then the whole thing will become much simpler. Also use enumerate instead of range.
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
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)
I have to write a program in python where the user is given a menu with four different "word games". There is a file called dictionary.txt and one of the games requires the user to input a) the number of letters in a word and b) a letter to exclude from the words being searched in the dictionary (dictionary.txt has the whole dictionary). Then the program prints the words that follow the user's requirements. My question is how on earth do I open the file and search for words with a certain length in that file. I only have a basic code which only asks the user for inputs. I'm am very new at this please help :(
this is what I have up to the first option. The others are fine and I know how to break the loop but this specific one is really giving me trouble. I have tried everything and I just keep getting errors. Honestly, I only took this class because someone said it would be fun. It is, but recently I've really been falling behind and I have no idea what to do now. This is an intro level course so please be nice I've never done this before until now :(
print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print
choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice
while choice != "q":
if choice == "a":
#wordlen = word length user is looking for.s
wordlen = raw_input("Please enter the word length you are looking for: ")
wordlen = int(wordlen)
print wordlen
#letterex = letter user wishes to exclude.
letterex = raw_input("Please enter the letter you'd like to exclude: ")
letterex = letterex.lower()
print letterex
Here's what you'd want to do, algorithmically:
Open up your file
Read it line by line, and on each line (assuming each line has one and only one word), check if that word is a) of appropriate length and b) does not contain the excluded character
What sort of control flow would this suggest you use? Think about it.
I'm not sure if you're confused about how to approach this from a problem-solving standpoint or a Python standpoint, but if you're not sure how to do this specifically in Python, here are some helpful links:
The Input and Output section of the official Python tutorial
The len() function, which can be used to get the length of a string, list, set, etc.
To open the file, use open(). You should also read the Python tutorial sec. 7, file input/output.
Open a file and get each line
Assuming your dictionary.txt has each word on a separate line:
opened_file = open('dictionary.txt')
for line in opened_file:
print(line) # Put your code here to run it for each word in the dictionary
Word length:
You can check the length of a string using its str.len() method. See the Python documentation on string methods.
"Bacon, eggs and spam".len() # returns '20' for 20 characters long
Check if a letter is in a word:
Use str.find(), again from the Python sring methods.
Further comments after seeing your code sample:
If you want to print a multi-line prompt, use the heredoc syntax (triple quotes) instead of repeated print() statements.
What happens if, when asked "how many letters long", your user enters bacon sandwich instead of a number? (Your assignment may not specify that you should gracefully handle incorrect user input, but it never hurts to think about it.)
My question is how on earth do I open the file
Use the with statement
with open('dictionary.txt','r') as f:
for line in f:
print line
and search for words with a certain length in that file.
First, decide what is the length of the word you want to search.
Then, read each line of the file that has the words.
Check each word for its length.
If it matches the length you are looking for, add it to a list.