How to put string inside string (variable) in Python? - python

I tried to run some python code, but it says "[pyflakes] unexpected EOF while parsing"
My code is:
if "debug " in code:
print(" |" + x + "|" + y + "| ")
Edit: Also do NOT say duplicate I tried the answer of the other question and it didn't work. I use Python 3.8.2

Try using an f-string.
if "debug " in code:
print(f" | {x} | {y} | ")

Related

Python - newline if variable is in print function, need fix [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have one problem with print in Python, I am starting to learn Python, but when I want to print variables in print function, it looks like that after one variable it adds newline to the outcome:
print(game_name + " | " + rating)
I am making a game database with my own ratings on the games but if it prints the game and the rating there is like one empty line belpw the game_name and rating is written, how can I delete that empty newline? I am very new to this, so please don't be mean...
Welcome to Stack Overflow! The most likely culprit is that there is a newline at the end of the game_name variable. The easy fix for this is to strip it off like this:
print(game_name.strip() + " | " + rating)
Say we had two variables like this.
game_name = 'hello\n'
rating = 'there'
game_name has the newline. To get rid of that use strip().
print(game_name.strip() + " | " + rating)
output
hello | there
If you want to remove the line break after printing, you can define the optional end parameter to the print statement.
print('Hello World', end='') # No new line
If your variable has a new line added to it, and you want to remove it, use the .strip() method on the variable.
print('Hello World\n'.strip()) # No empty line
For your code, you could run it:
print(game_name + " | " + rating, end='')
Or
print(game_name + " | " + rating.strip())
If the error is that a new line is printed after game_name, you'll want to call the strip method on that instead.
print(game_name.strip() + " | " + rating)
rating or game_name most likely have a new line after the specified string.
You can fix it by doing this:
game_name = game_name.strip('\n')
rating = rating.strip('\n')
print(game_name + " | " + rating)

Python 2 Sorting from a text file [duplicate]

This question already has answers here:
I have wrong results with sorting function at python
(2 answers)
Closed 2 years ago.
Im trying to write a code where user puts in their score (a number), and then they put in their name. both the score and name gets stored in a text file (alongside with '\n', so that every new couple gets stored on the new line).
hscores = open("highscores.txt", "a")
hscores.write(str(score))
hscores.write(" ")
hscores.write(nickname)
hscores.write("\n")
hscores.close()
then, I open the text file, take every input in there, sort it by highest to lowest and output it:
hscores22 = open("highscores.txt", "r")
listings2 = hscores22.readlines()
sorting2 = sorted(listings2, reverse=True)
print "| 1 | " + sorting2[0]
print "| 2 | " + sorting2[1]
print "| 3 | " + sorting2[2]
print "| 4 | " + sorting2[3]
print "| 5 | " + sorting2[4]
print "| 6 | " + sorting2[5]
print "| 7 | " + sorting2[6]
print "| 8 | " + sorting2[7]
print "| 9 | " + sorting2[8]
print "| 10 | " + sorting2[9]
The problem is that python thinks that number that starts with the biggest number, is bigger, for example: 90>1000, 50>100 (I suppose thats because i have to convert all the numbers to strings before storing them in the text file). is there any way i could fix this?
thanks in advance.
Since you're sorting strings, Python is comparing them lexicographically - so '2' is bigger than '1'. You need to extract the numeric part of your string, convert it to a number and use this number for sorting key:
sorting2 = sorted(listings2, reverse=True, key=lambda x: int(x.split()[0]))
BTW, next 10 lines really ask to be replaced by a for loop…

argument of type 'int' is not iterable Issue

What I trying to do is picking random integers from a value, for example: 1:32 will be an input, I will split by the : and then select a random value. Then Selenium will select the dropdown based on what value is returned.
My code:
# SELECT
if register_parts[3] == "SELECT":
if register_parts[0] + '="' + register_parts[1] + '"' in self.driver.page_source:
_select_value = ""
if ":" in register_parts[2]:
_select_value = self.get_random_value_between(register_parts[2])
_select = Select(selenium_action)
_select.select_by_visible_text(_select_value)
self.write_to_debug_file("self.select_by_visible_text(" + _select_value + ") --> SELECT --> [ " + _select_value + " ]")
else:
_select_value = register_parts[2]
_select = Select(selenium_action)
_select.select_by_visible_text(_select_value)
self.write_to_debug_file("self.select_by_visible_text(" + _select_value + ") --> SELECT --> [ " + _select_value + " ]")
Additional function:
def get_random_value_between(self, input_values):
''' this function will return a random value between: x:x or 1:31 for example ... '''
parts = input_values.split(':')
return random.randrange(int(parts[0]), int(parts[1]))
The problem is on this line:
_select.select_by_visible_text(_select_value)
I'm getting the error:
argument of type 'int' is not iterable
From reading up, I think the issue lies in the fact I am doing:
if ":" in
I could be wrong. I'm not sure how to fix it. Any help on the issue would be appreciated. As far as I can see, the code should work, but I must be missing something. I have read a few threads on here regarding the error but it's still not sinking totally in.
If possible, cast _select_value as string before using _select.select_by_visible_text.
And recast as int values after the iteration.
I think this is correct. If the error is on if and not the else, then your passing an Int as an argument to a method that needs a text/str value.
Just try the following line:
_select.select_by_visible_text(str(_select_value))

Can not print on same line in python. Neither print("string here", end = "") nor does print "something", work

I want to print multiple statements on the same line in python 3.7. I have tried both using the print " string", and print("Something",end = " ") but neither work. Both give syntax errors.
print 'Checkout: ',
Gives
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Checkout: ', end=" ")
Ironically when using:
print('Checkout: ', end = " ")
I get a red line under the = " " part saying unexpected expression syntax.
Edit: The problem was that the IDE was essentially running in 2.* mode. Even though there was a red line under the end = " " part it compiled and ran fine.
Well, in Python 3.* the print "Checkout" isn't going to work because Python 3.* requires the parenthesis. If you would like to print multiple statements on the same line you could try something like this,
print("Checkout: , Tax: , Balance: ")
If you are interested in placing values in the blank spots then, perhaps you could try this,
print("Checkout: {0}, Tax: {1}, Balance: {2}".format(100, 0.8, 100.8))
I hope this helps.

TypeError: Can't convert 'builtin_function_or_method' object to str implicitly

I'm making a simple mad libs program in python 3 where the user enters in nouns and pronouns and the program is supposed to print out the inputs from the user.
Here is my code:
print ("Welcome to Mad Libs. Please enter a word to fit in the empty space.")
proper_noun = input("One day _________ (Proper Noun)").lower()
ing_verb = input("Was __________ (Verb + ing) to the").lower()
noun1= input("to the _________ (Noun)").lower()
pronoun1 = input("On the way, _____________ (Pronoun)").lower()
noun2 = input("Saw a ________ (Noun).").lower
pronoun2 = input("This was a surprise so ________ (Pronoun)").lower()
verb2 = input("_________ (verb) quickly.").lower()
#Asks user to complete the mad libs
print ("One day " + proper_noun)
print ("Was " + ing_verb + " to the")
print (noun1 + ". " + "On the way,")
print (pronoun1 + " saw a " + noun2 + ".")
print ("This was a surprise")
print ("So " + pronoun2 + " " + verb2 + " quickly.")
Getting this error code: TypeError: Can't convert 'builtin_function_or_method' object to str implicitly
On this line:
print (pronoun1 + " saw a " + noun2 + ".")
Fairly new to python, so i'm not entirely sure what this error means and how to fix it, can somebody explain this error code to me please?
The issue is with the noun2 variable
noun2 = input("Saw a ________ (Noun).").lower
You are assigning the function .lower to it , not the result of calling it . You should call the function as .lower() -
noun2 = input("Saw a ________ (Noun).").lower()
For Future readers
when you get an issues such as - TypeError: Can't convert 'builtin_function_or_method' object to str implicitly - when trying to concatenate variables contain strings using + operator.
The issue basically is that one of the variables is actually a function/method, instead of actual string.
This (as in the case with OP) normally happens when you try to call some function on the string, but miss out the () syntax from it (as happened in the case of OP) -
name = name.lower #It should have been `name.lower()`
Without the () syntax, you would be simply assigning the function/method to the variable , and not the actual result of calling the function. To debug such issues you can check out the lines where you are assigning to the variables , used in the line throwing the error, and check if you missed out on calling any function.

Categories

Resources