This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 1 year ago.
I'm trying to make a Madlibs-type thing in python, as I'm new to coding and wanted a sort of simple project to work on for a first thing to make. I'm trying to make it so that the verbs/nouns/adjective variables appear in the string, but they, instead of being called, are just right in the code. This is the first actual program that I've written, so this is probably a super easy fix, but I have no idea how to make this work.
print("Welcome To Madlibs")
choosepage = input("Choose Page, 1, 2 or 3. :\n")
choosepage = int(choosepage)
if choosepage == 1:
print("Welcome To Madlibs, Page 1")
adjective1 = input("Give One Adjective: ")
noun1 = input("Give One Noun: ")
noun2 = input("Give Another Noun: ")
verb1 = input("Give A Verb: ")
adjective2 = input("Give Another Adjective: ")
print("One Day, there was a "%adjective1" woman. This woman, was on a walk one day, when she saw a " %noun1 " She looked at the " %noun1 " and thought to herself, " %noun1 " looks like a " %noun2 "."
elif choosepage == 2:
print("Welcome To Madlibs, Page 2")
(The Code in Question)
The reason I'm putting % signs in front of the variables is because I saw that as a fix somewhere online.
You're looking for string formatting, which can use the .format() method or can be an "f-string" .. many helpful options exist for formatting numbers (such as padding)
>>> word = "airport"
>>> "they went to the {}".format(word)
'they went to the airport'
>>> f"they went to the {word}"
'they went to the airport'
Use f-strings:
print(f"One Day, there was a {adjective1} woman. This woman, was on a walk one day, when she saw a {noun1}. She looked at the {noun1} and thought to herself, {noun1} looks like a {noun2}."
Python 3.6 introduced f-strings, which makes it super easy to use variables in-line in a string. All you have to do is add the 'f' flag prior to your opening quote. They work as follows:
print(f"One Day, there was a {adjective1} woman. This woman, was on a walk one day, when she saw a {noun1} She looked at the {noun1} and thought to herself, {noun1} looks like a {noun2}.")
These have the advantage of being much clearer and easier to format than traditional string formatting in cases like this.
Related
So, pretty new with coding in general and im running into an issue. My assignment this week is to run a quick program that takes a name, and age and spit out a quick prompt repeating the name and stating a birth year. the big problem is PyCharm is putting everything in quotations.
So, with my input
user_name = raw_input('Enter your name:')
user_age = int(input('Enter your age:'))
birth_year = (2022 - user_age)
print('Hello', user_name+'!' ' ' 'You were born in', birth_year)
I am getting the output
Enter your name:Ryan
Enter your age:27
('Hello', 'Ryan! You were born in', 1995)
Process finished with exit code 0
Is this just something PyCharm does? I would love to get rid of all the quotation marks, but I also don't know if im just being too picky about formatting. I appreciate any advice!
You are using a combination of , and + to concatenate strings and some (seemingly) random '. This should work:
print('Hello ' + user_name + '! You were born in ' + str(birth_year))
The problem with your implementation is that python turns your output into a tuple (because of the ,) with the values you are seeing in your output.
Well, for starters, it looks like you’re using python 2. This is generally a bad idea when you start, as python 3 is used much more. But to answer your question, you aren’t printing out one string. Instead, you are printing a string ‘Hello ‘ then a completely different string, then an integer. The best way to print multiple variables in the same string is to use the built-in f’’ command. Simply use print(f’Hello, {user_name}! You were born in {birth_year}.’). However, I’m not sure if this is compatible with python 2.
I am using notepad++ to write code for python and have a variable that I need to add 1 to for my next question. I am new to coding and would like to know how to achieve this. I would also like to phrase the question so that the answer (variable plus 1) is placed between text. Below, in my next line I would like it to read (for instance if the number is 3) How often do the 4 of you visit?
I have tried different ways of framing my variable +1 within parentheses and quotation marks but at best, when run, it shows exactly what I wrote not the answer to the equation.
famnumber = input ("How many of your family members still live there?")
I would like the answer to appear within text as noted above if possible.
Here is some code:
famadd = float(famnumber) + (1)
print ("Do all (famadd) of you get together often?")
There are several ways to do this. Note that when you you get something from input, it's a string. So using famnumber += 1 won't work, as you can't add a number to a string. So we have to turn the numeral string into an actual number. You can use int() to convert the input text into an integer. Then to include the value in a new string for your next question, use %d ('d' for 'digit'). This makes more sense than using a float, since people don't report family members in fractions of whole numbers (likewise, you don't want to say something like 'How often do the 4.0 of your meet?').
famnumber = input("How many of your family members still live there? ")
new_number = int(famnumber) + 1
next_question = input("How often do the %d of you meet? " % new_number)
Other ways to accomplish the same thing is converting 'famnumber' itself from a string to an integer, then back into a string to join in the sentence. Personally I'd go with the previous method, but this should give you an idea of some of the other things you can do in Python:
famnumber = input("How many of your family members still live there? ")
famnumber = int(famnumber)
famnumber += 1
next_question = input("How often do the " + str(famnumber) + " of you meet? ")
Also, while Notepad++ is a great text editor, if you're planning on doing a lot of Python scripting and writing, you may want to consider instead using an IDE, such as PyCharm, or IDLE which is included in the Python package. Tools like this make it easier for yourself to read and run your code.
I think you are looking for this kind of code:
famnumber = input("How many of your family members still live there?")
incremented_number = int(famnumber) + 1
next_number = input("How often do you " + str(incremented_number) + "visit")
print(next_number)
In the second line simply cast the input to int and increment it by one.
In the third line put the variable where you want it to be shown surrounded by + signs. You have to cast it to a string by using str() because the return type itself is a string. You can verify the type of the variable next_number simply by adding this line print(type(next_number))
This question already has an answer here:
Why doesn't the result from sys.stdin.readline() compare equal when I expect it to?
(1 answer)
Closed 6 years ago.
Im new to this so Im sorry if this isn't the best way to ask the question...
here is the code -
import sys
print("What is ur name?")
name = sys.stdin.readline()
answer = "jack"
if name is answer :
print("ur awesome")
exit();
right now when I run it in cmd I don't get anything printed even though
I input - jack? thank you in advance
Firstly, replace is with ==. is checks whether the two underlying strings are the same entity (in memory) whereas == just wants to check if they have the same value.
Because the source of "jack" is coming from two sources (one from the user, another hard-coded by you) they are two seperate objects.
As #dawg mentioned you also have to use the .strip() to get rid of the newline when using sys.stdin.readline() for input. The best way to read input is to use the input() method in python3, or raw_input() in python2.
name = input('What is your name?\n')
Use == for string comparison. Also, readline() will include the newline at the end of the string. You can strip it with e.g.
name = name.strip()
Alternatively, you can use raw_input() (input() in python 3) instead of readline(), as it will not include the newline to begin with.
name = raw_input("What is your name?\n")
It's helpful to be able to print a string to see if it has any extra whitespace, e.g.
print("name: [%s]\n" % name)
I'm following the built-in tutorial in PyCharm Edu Edition and I'm stuck on Strings - Character Escaping.
In the exercise I'm asked to print the following:
The name of this ice-cream is "Sweeet'n'Tasty"
by using character escaping, and here's my code:
print("The name of this ice-cream is \"Sweeet\'n\'Tasty\"")
and it still gives me "Sorry the wrong string is printed". Honestly I don't think I printed a wrong string. Any help?
The last print statement uses single quotation marks, so the test wants you to only escape the single quotes that surround the 'n', so this line worked for me:
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
You have to escape " because you use it in your print but your ' does not need to be protected.
Printing "\'n" and "'n" will output the same line but the escape, even if not visible, will generate something that is read by your exercise controller.
Try removing the \ before the '
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
Another solution for string containing " or ' is to use triple " like this:
print("""The name of this ice-cream is "Sweeet'n'Tasty\"""")
In this very case, the fact that the sentence is terminated by a " force to protect it again, but the " in the middle does not need to be protected.
You can also invert the use of ' and " to protect the ' or the "
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
And use of 3 ' is possible too:
print('''The name of this ice-cream is "Sweeet'n'Tasty"''')
If that still don't work, could you provide the assert test ?
Edit:
This seems to be the issue you are facing: http://iswwwup.com/t/d08b1b05234e/print-out-text-using-one-string-in-python.html
Comes from an ambigous test requirement / IDE behaviour.
dont_worry = "Don't worry about apostrophes"
print(dont_worry)
print("The name of this ice-cream is \"Sweeet\"")
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
This problem can only be resolved if double quote is used(accoording to test file)
Anyway, if you try this it will help you to finish succesfully:
print("\'The name of this ice-cream is \"Sweeet'n'Tasty\" \'")
The instructions in those lessons are not clear at all and someone from jetbrains should look into this.
Even tho they don't mention it in the instructions, they also want you to edit the third line:
print("The name of this ice-cream is \"Sweeet\"")
to this:
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
No need to escape double quotes in the fourth line:
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
So the complete code should look like this
dont_worry = "Don't worry about apostrophes"
print(dont_worry)
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
Also, this worked for me:
print("The name of this ice-cream is \"Sweet'n'Tasty\"")
I'm new to coding (any kind), and so this is just a guess - the solution requires that you print only one string, so perhaps \"Sweet\'n\'Tasty\" is read as multiple strings? Like I said, real beginner. (also, could be that sweet was spelled wrong?)
I have the same problem.
The string is correct, but it still says I got the wrong string. Then I found that my answer is outside of the answer placeholder, just reset the task and the problem was solved.
print('The name of this ice-cream is "Sweet\'n\'Tasty"')
I'm using Python 3.1 to write a simple game involving naming state capitols. I think I have some kind of type mismatch but I don't know what it is.
I think it's when I compare the player's answer to the real answer, but don't know how to make it right.
from random import *
states = {}
print ("Guess State Capitols")
statefile = open("state capitols.csv")
for line in statefile:
(state,capitol) = line.split(",")
states[state] = capitol
statefile.close()
guessnum = randint(1,50)
names = list(states.keys())
guess = names[guessnum]
print("What is the capitol of " + guess)
playerguess = input()
if playerguess == str(states[guess]):
print("Yes You are right!")
print("No you are wrong")
print(str(states[guess]))
It's at
if playerguess == str(states[guess]):
but I don't know what I am doing wrong, in that even when I have the answer right, it says I'm wrong, but prints the same answer I typed in.
I know it's a newbie question, but would appreciate any help.
(I also know that the line "no you are wrong" would print in any case, but I'll fix that later).
You can use two "prints" to debug it:
print(playerguess)
print(states[guess])
this should give you the hint.
I would say that when you got your capitol from your csv file you didnt take out the newline.
So maybe this will work:
for line in statefile:
(state, capitol) = line.strip().split(",")
states[state] = capitol
statefile.close()
If you have a type mismatch then you will get a traceback with lots of useful information. I'll assume that since you haven't posted one you didn't get a traceback, so it isn't a type mismatch.
When you're trying to find a problem like this you should try printing the repr() of the string:
print(repr(playerguess))
print(repr(states[guess]))
That will show you exactly what is in each string, including any trailing whitespace or newlines.