Putting quotation marks inside a string - python

def add_div(filename, caption):
test = str(filename)
return ('<div><img src=' + test + '><br><p>' + caption + '</p></div>')
def add_body(image_dict, s, order = None):
'''(dict of {str:list of str}, str, list) -> str
If the third parameter is passed, then the filenames
included in the body should only be those in the list and should be added
in the same order as they are listed in the list. '''
new = ''
s = '<html><head></head>'
while order is None:
for (key, value) in image_dict.items():
new += add_div(str(key), str(value[2]))
return (s + '<body><div id="slideshow">' + new + '</body>'+ '</html>')
The output of add_body function is:
how do I get quotation marks around the word images/skater.jpg ?
this is what the file looks like

You have two separate options:
1) Use double quotes
print("Hey that's pretty cool!")
2) Escape the single quotation mark
print('Hey that\'s pretty cool!')

You can include the quotation marks in the string that you are concatenating like this :
def add_div(filename, caption):
test = str(filename)
return ('<div><img src="' + test + '"><br><p>' + caption + '</p></div>')

Use one type of quotation for the string definition and the other for the included quotes:
>>> "bob said: 'hello'"
"bob said: 'hello'"
>>> "I said 'yo bob, how u doing?' in reply"
"I said 'yo bob, how u doing?' in reply"
So to fix your problem, just change the return statement in the first function to:
return ('<div><img src="' + test + '><br><p>'" + caption + '</p></div>')
Note that as a final thing, the parenthesis in the return statement aren't required as return is a not a function or method.

Good answers, but another method is to escape the single or double quotation mark with \
Example:
# this is the same as
# s = "'"
s = '\''
print(s)
#this is the same as
# s = '"'
s = "\""
print(s)

Related

Python - (if/else) extra characters?

So I'm doing my homework but I can't seem to figure out how to add "extra" characters to regular statement.
I want this code to say that lname have to consist only from letters and " " or/and "-" symbols and can't start with " ". How can I achieve this? I don't even know what to search for or try. Isn't there some kind of “includes” function built in? I'm getting desperate.
def perenimi2():
global lname
lname = perenimi.get()
if lname.isalpha():
textVar.set("")
nd2 = {"Perenimi": str(lname)}
uusklient.update(nd2)
post2()
else:
textVar.set ("Sisestage korrektne perekonnanimi!")
What I mean is how can I make IF statement that MUST include letters and may also include "-" or/and space. I want to make fname to be only letters and "-" or/and space. (This is for a name field which also can't start with space)
I'm sorry if this has been asked before but I haven't been able to find the solution.
-----CODE AFTER USING POSTED ANSWER-----
With the posted answer I found a new problem, it now allows input or entry to be empty which can't be empty.
I translated everything to English.
import string
###FirstName
def firstname1():
global fname
allowed = " -"
cantStart = " "
fname = firstname.get()
if (set(fname) <= set(allowed + string.ascii_letters) and not fname.startswith(cantStart)):
textVar.set("")
familyname2()
elif fname == "":
textVar.set("Insert correct name!")
else:
textVar.set("Insert correct name!")
###FamilyName
def familyname2():
global lname
lname = familyname2.get()
allowed = " -"
cantStart = " "
empty = ""
if (set(lname) <= set(allowed + string.ascii_letters) and not lname.startswith(cantStart)):
textVar.set("")
post2()
elif lname == "":
textVar.set("Insert correct family name!")
else:
textVar.set("Insert correct family name!")
firstname1()
import string
ALLOWED = " -"
CANT_START = " "
if (set(lname) <= set(ALLOWED + string.ascii_letters)
and not lname.startswith(CANT_START)
and lname):
No elif branch (i.e. remove it from your code).
The explanation:
string.ascii_letters is "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
set(lname) is the set of all characters in lname, e. g. if lname == "abba", then set(lname) will be "ab".
The <= operation between two sets means “is a subset of”, i.e. if all elements in the left set exist in the right set, too.
lname is True only for nonempty strings (you may also use lname != "", but using only lname is more Pythonic).
The long expression in the if branch is surrounded with parentheses only for the possibility to split it freely into more lines, i.e. without the necessity to end every non-complete line with the continuation symbol (\). Otherwise, it has to be in the form as
if set(lname) <= set(ALLOWED + string.ascii_letters) \
and not lname.startswith(CANT_START) \
and lname:
(or be written fully only in one, very long line).

I need to input the print from this function into a tkinter page

I have this function that prints 25 lines of text and I need to input it in my tkinter page, but ever time it doesn't seem to work.
I've tried using text.input but it didn't seeem to work
This is the function I need to print:
def decode(secretmessage):
for key in range(len(alphabet)):
newAlp = alphabet[key:] + alphabet[:key]
attempt = ""
for i in range(len(message)):
index = alphabet.find(message[i])
if index < 0:
attempt += message[i]
else:
attempt += newAlp[index]
print("Key: " + str(key) + " - " + attempt)
print()
This is what I tried:
def finalprint (uncoded):
print("Key: " + str(key) + " - " + attempt)
print()
text = Text.insert(root, finalprint(message), width=450, height=450)
It doesn't work to show up for some reason.
The print command prints the given text to console. It does returns None
Your finalprint function also returns None while Text.insert expects a string as an input.
Instead of printing the output you can store the values into a string.
def finalprint(uncoded): ## may need different inputs as key and attempts are not in scope
string = ""
string = string + "Key: " + str(key) + " - " + attempts + "\n"
return string
However the input to the finalprint function is uncoded while the variables used in it are key and attempts. You may need to pass in more information to the function for it to work like you have it written.

How can I split string into variables?

I need to split the string into variables something like:
string = "Hello: My name is..."
title, separator, my_name_is = string.partition(": ")
But, I need a string with "My name is..." always in variable 'my_name_is' even if in the initial string will be only "My name is...".
I think it could be done something like this:
>>>string = "My name is..."
>>>title, separator, my_name_is = string.partition(": ")
>>>if my_name_is == "":
>>> my_name_is = title
>>>print(my_name_is)
My name is...
but I must have this code in one line and can't use the RE (task for the school)
If it has to be in one line without any imports, then this will do the job quite nicely:
string = "Hello: My name is..."
(title, my_name_is), separator = string.split(': ') if ':' in string else (None, string), ':'
print(title)
print(separator)
print(my_name_is)
# Hello
# :
# My name is...
This works also if the string has no 'title':
string = "My name is..."
(title, my_name_is), separator = string.split(': ') if ':' in string else (None, string), ':'
print(title)
print(separator)
print(my_name_is)
# None
# :
# My name is...
I would never ever do such awful oneliners though.

How to print the for loop as the last thing in a function?

So here is my function and some info on it:
This function is called by another function, so returning the result1 would print what I want.
So, in this function, I want to be able to print result1 then the for loop after; although, since I am unable to place the for loop inside the return, it would always print the for loop first, then the returned result1 would be printed next.
Note: Dish_str() is another function, I will include it at the bottom
def Restaurant_str(self: Restaurant) -> str:
result1 = ("Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: ")
for i in self.menu:
print(Dish_str(i))
return result1 + "\n\n"
This is the result:
Fried Chicken ($10.00): 1300.0cal
Name: KFC
Cuisine: American
Phone: 1112223333
Menu:
I want to make it so that the dish would come after the menu.
One way that I attempted to make it work was putting the Dish_str() into the return so it would look like this:
return result1 + Dish_str(self.menu) + "\n\n"
To which, I'd receive an error that says an attribute error saying that the list does not contain attribute name, even though in the for loop, it was able to work. Then I tried doing simply just Dish_str(self) which gives me a type error that can't concatenate a list.
Another way I tried to make it work was also split the for loop into another function and have the Restaurant_str() call it, but alas, no avail because I realized it was the same exact thing as calling Dish_str() just with another extra function.
Here is the other functions that are calling it and being called on:
def Dish_str(self: Dishes) -> str:
'''Returns a string that represents the dish name, price, and calories'''
result = self.name + " ($" + str("%.2f" % self.price) + "): " +
str(self.calories) + "cal"
return result
def Collection_str(C: list) -> str:
''' Return a string representing the collection
'''
s = ""
for r in C:
s = s + Restaurant_str(r)
return s
I simply print the collection through:
print(Collection_str(C))
Please let me know if you need me to clarify anything as I wrote this late at night and didn't have time to check in the morning. Thank you for your patience and help in advance.
Just add the string dish to the end of result1, result1 = result1 + Dish_str(i)
def Restaurant_str(self: Restaurant) -> str:
result1 = ("Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: ")
for i in self.menu:
result1 = result1 + Dish_str(i)
return result1 + "\n\n"
Would this help?

string.replace('the','') is leaving white space

I have a string that is the name of an artist that I get from the MP3 ID3 tag
sArtist = "The Beatles"
What I want is to change it to
sArtist = "Beatles, the"
I have running into 2 different problems. My first problem is that I seem to be trading 'The' for ''.
if sArtist.lower().find('the') == 0:
sArtist = sArtist.lower().replace('the','')
sArtist = sArtist + ", the"
My second problem is that since I have to check for both 'The' and 'the' I use sArtist.lower(). However this changes my result from " Beatles, the" to " beatles, the". To solve that problem I just removed the .lower and added a second line of code to explicitly look for both cases.
if sArtist.lower().find('the') == 0:
sArtist = sArtist.replace('the','')
sArtist = sArtist.replace('The','')
sArtist = sArtist + ", the"
So the problem I really need to solve is why am I replacing 'the' with <SPACE> instead of <NULL>. But if somebody has a better way to do this I would be glad for the education :)
Using
sArtist.replace('The','')
is dangerous. What happens if the artist's name is Theodore?
Perhaps use regex instead:
In [11]: import re
In [13]: re.sub(r'^(?i)(a|an|the) (.*)',r'\2, \1','The Beatles')
Out[13]: 'Beatles, The'
One way:
>>> def reformat(artist,beg):
... if artist.startswith(beg):
... artist = artist[len(beg):] + ', ' + beg.strip()
... return artist
...
>>> reformat('The Beatles','The ')
'Beatles, The'
>>> reformat('An Officer and a Gentleman','An ')
'Officer and a Gentleman, An'
>>>

Categories

Resources