End of statement expected while using Dot Format - python

I need to print the following of code :
print('hello "my friend '{}' "'.format(name))
such that the output is:
'hello "my friend 'ABCD' " '
But I get the error: End of Statement expected
What is the correct syntax?

You need to escape quotes if you want to use them in a string:
print('hello "my friend \'{}\'"'.format(name))

Try this,
print("""hello "my friend '{}' " """.format(name))

Related

How to add two user data inputs in python?

Write a Python program that takes the user's name as input and displays and welcomes them.
Expected behavior:
Enter your name: John
Welcome John
The Python code for taking the input and displaying the output is already provided
#take the user's name as input
name = input("Enter your name: ")
print(name)
#the vaiable that includes the welcome message is alredy provided.
#Please complete this part using the knowledge obtained in this lesson.
greeting = ("Welcome John")
#print the welcome message
print(greeting)
Out put I got with one error
greeting = (f' Welcome {name}')
Or
greeting = ('Welcome ' + name )
The problem I see is an error in your code where you have hard coded the name "John" with the output. What you ought to do instead, is to output the Variable alongside the greeting message.
greeting = (f"Welcome {name}")
Using this will output the welcome message alongwith the name that's entered. What I have done is used an F-string however there's other ways to do it as well. Hope that answer's your question.
You have hard coded the greeting
greeting = ("Welcome John")
Given you have a name the user has provided, you can use string formatting to interpolate that name into your greeting like this:
greeting = (f"Welcome {name}")
(Notice, you put the variable in curly braces)
# take the user's name as input
name = input("Enter your name: ")
print(name)
# Please complete this part using the knowledge obtained in this lesson.
greeting = ("Welcome" +" "+ name)
# print the welcome message
print(greeting)

How to parse answers with deepl api?

I want to use deepl translate api for my university project, but I can't parse it. I want to use it wit PHP or with Python, because the argument I'll pass to a python script so it's indifferent to me which will be the end. I tried in php like this:
$original = $_GET['searchterm'];
$deeplTranslateURL='https://api-free.deepl.com/v2/translate?auth_key=MYKEY&text='.urlencode($original).'&target_lang=EN';
if (get_headers($deeplTranslateURL)[0]=='HTTP/1.1 200 OK') {
$translated = str_replace(' ', '', json_decode(file_get_contents($deeplTranslateURL))["translations"][0]["text"]);
}else{
echo("translate error");
}
$output = passthru("python search.py $original $translated");
and I tried also in search.py based this answer:
#!/usr/bin/env python
import sys
import requests
r = requests.post(url='https://api.deepl.com/v2/translate',
data = {
'target_lang' : 'EN',
'auth_key' : 'MYKEY',
'text': str(sys.argv)[1]
})
print 'Argument:', sys.argv[1]
print 'Argument List:', str(sys.argv)
print 'translated to: ', str(r.json()["translations"][0]["text"])
But neither got me any answer, how can I do correctly? Also I know I can do it somehow in cURL but I didn't used that lib ever.
DeepL now has a python library that makes translation with python much easier, and eliminates the need to use requests and parse a response.
Get started as such:
import deepl
translator = deepl.Translator(auth_key)
result = translator.translate_text(text_you_want_to_translate, target_lang="EN-US")
print(result)
Looking at your question, it looks like search.py might have a couple problems, namely that sys splits up every individual word into a single item in a list, so you're only passing a single word to DeepL. This is a problem because DeepL is a contextual translator: it builds a translation based on the words in a sentence - it doesn't simply act as a dictionary for individual words. If you want to translate single words, DeepL API probably isn't what you want to go with.
However, if you are actually trying to pass a sentence to DeepL, I have built out this new search.py that should work for you:
import sys
import deepl
auth_key="your_auth_key"
translator = deepl.Translator(auth_key)
"""
" ".join(sys.argv[1:]) converts all list items after item [0]
into a string separated by spaces
"""
result = translator.translate_text(" ".join(sys.argv[1:]), target_lang = "EN-US")
print('Argument:', sys.argv[1])
print('Argument List:', str(sys.argv))
print("String to translate: ", " ".join(sys.argv[1:]))
print("Translated String:", result)
I ran the program by entering this:
search.py Der Künstler wurde mit einem Preis ausgezeichnet.
and received this output:
Argument: Der
Argument List: ['search.py', 'Der', 'Künstler', 'wurde', 'mit', 'einem',
'Preis', 'ausgezeichnet.']
String to translate: Der Künstler wurde mit einem Preis ausgezeichnet.
Translated String: The artist was awarded a prize.
I hope this helps, and that it's not too far past the end of your University Project!

What does F do in python flask before string?

#app.route("/<name>")
def office(name):
return F"Hello {name}! "
What is the F doing before "Hello {name}! "?
These are called "f-strings" and are not limited to Flask. It's basically a string formatting mechanism used in Python.
Suppose you have a variable name = "XYZ". Using
print ('Hello {name}')
will print "Hello {name}", which is not what you want. Instead, you use an f-string so you can have the value {name} be the same as your variable.
print (f'Hello {name}')
The above would print "Hello XYZ". Alternatively, you could also use the following:
print ('Hello {}'.format(name))
You can read about them in more detail here: https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/

Syntax Error CGI script

name = form.getvalue('name')
age = form.getvalue('age') + 1
next_age1 = int(form["age"].value
print "Content-type: text/html"
print
print "<html><head>"
print "<p> Hello, %s</p>" % (name)
print "<p> Next year, you will be %s years old.</p>" % next_age1
Having trouble understanding why this doesn't work.
Can someone please help me?
Thank you!
You are missing a closing parenthesis:
next_age1 = int(form["age"].value
# ----^ -------^ nothing here
Rule of thumb: when you get a syntax error you cannot immediately spot on that line, look at the previous line to see if you balanced your parenthesis and braces properly.

String formatting: string specifier in a string constant

Is there a way to insert a string in a string constant/variable that contains a string specifier?
Example:
temp_body = 'Hello %s, please visit %s to confirm your registration.'
body = temp_body % (name, url)
But this raises a TypeError.
Usually it is the way strings are generated e.g. msg template will be loaded from db or some file and things inserted in between, what is url and name in your case?
This works on my machine
>>> temp_body = 'Hello %s, please visit %s to confirm your registration.'
>>> temp_body%("anurag", "stackoverflow")
'Hello anurag, please visit stackoverflow to confirm your registration.'
Also try if str(name), str(url) works , ost probably it won't and try to fix that problem instead.
Works on my machine(TM).
Are you sure that name and url really are strings? What do you get when you do
>>> type(name), type(url)

Categories

Resources