Is there any way to avoid printing out data (like quotations marks, brackets, commas and other important matematical symbols) when printing from a variable?
int1 = random.randint(1,100)
int2 = random.randint(1,100)
q1 = "What is", int1, "+", int2, "?"
answer = int(raw_input(q1))
The code above prints this:
('What is', 75, '+', 74, '? ')149
The proper way of printing the above would supposedly be this:
What is 75 + 74? 149
The "proper way" is to use str.format:
q1 = "What is {0} + {1}? ".format(int1, int2)
answer = int(raw_input(q1))
The clearest syntax I believe would be the one that separates the constant string from the variables:
print "What is %d + %d?" % (int1, int2)
Simple:
q1 = "What is" + str(int1) + "+" + str(int2) + "?"
or
' '.join([str(x) for x in q1])
Related
Suppose I have a string : ' Swarnendu Pal is a good boy '
Here I want to remove all the spaces in between the strings, that means the leading and the last spaces should be remain same but all other spaces should be removed. My final expected output will be : ' SwarnenduPalisagoodboy '
Try this... doesn't matter #spaces you have in the start/end... the code will retain them... & remove in between strings...
s = " Swarnendu Pal is a good boy "
start_space, end_space = 0,0
for i in s:
if i == " ":
start_space += 1
else:
break
for i in s[::-1]:
if i == " ":
end_space += 1
else:
break
result = " " * start_space + s.replace(" ","") + " " * end_space
print(result)
# " SwarnenduPalisagoodboy " #### output
Hope this helps...
An attempt at regular expression, which will remove consecutive white space characters with non white space characters outside both ends (I'm not very good at using it yet, and there may be a better solution):
>>> import re
>>> re.sub(r'(?<=[^ ]) +(?=[^ ])', '', ' Swarnendu Pal is a good boy ')
' SwarnenduPalisagoodboy '
I'm writing a program for myself that generates a loadout for this game I play. I'm nearly done, I switched from using random.choice to random.sample in order to avoid have repeats in the results but hate the formatting.
print("He has", random.choice(kills) + ',', random.choice(kills) + ',', random.choice(kills) + ', and', random.choice(kills))
Outputs:
He has Two Handed Choke, Skewer, Skewer, and Pitchfork Stab
whereas:
print("He has", random.sample(kills, 4))
Outputs:
He has ['Knee Snap', 'Jaw Rip', 'Body Slam', 'Choke']
How do I get a sample that outputs like the code for random.choice()?
Thanks!
random = random.sample(kills, 4)
str_random = ", ".join(str(x) for x in random[:-1])
print("He has", str_random, "and", random[-1])
One way to do this is to iterate over the object, adding it to a string. Try the following:
choices = random.sample(kills,4) #put choices in variable
s = "He has " #begin output String
for(c in choices):
s = s + c + "," #add choices to output string
s = s[:-1] #remove final comma
print(s) #print string
I'm trying to make an algorithm in Python 2.7.10 that takes user input, splits it and puts words into a list, then takes all words from that list and prints them in a specific manner.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
print "You think that the painting is:"
print "%s" + ", %s" * len(input) + "." % ( > ? < )
The %s formatters work as placeholders. The problem is that the number of placeholders that will be printed as a part of the string isn't fix, it's equal to len(input). Therefore I don't know how to assign values to these formatters. (That's the " > ? < " part inside of the brackets.)
Note: as this is for test purposes only, let's assume the user will only be inputting strings, not integers, etc. so that there is no need for the %r formatter.
The desired output should look somewhat like this:
> nice pretty funny
You think that the painting is:
nice, pretty, funny.
I know this can be achieved using the str.join(str) method but is there a way of doing it as I explained above? Thanks.
Use print ("%s" + ", %s" * (len(input) - 1) + ".") % tuple(input)
However, IMO ', '.join(input) + '.' is better :)
You can do what you want by doing this:
print ",".join(["%s"] * len(input)) % tuple(input)
Basically, construct your string of "%s, "... and pass the input as a list to the string formatters. You can do it exactly like you've written it too, just pass in your list.
print "%s" + ", %s" * len(input)) + "." % tuple(input)
You should use a tuple after "%". Note that you have already considered the first word in the print, so len(input) -1 words are left to be written.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
output = "%s" + ", %s" * (len(input) - 1) + "."
print "You think that the painting is:"
print output % tuple(input)
I've been working on HTTLCS and am having some difficulty finishing up the problem.
Solving a problem was not much of an issue, but I have trouble returning my result as a string rather than the tuple data type.
Here is my code:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains", wordnum, "words, of which" , eWordnum , "(" , percent , "%)" , "contains an 'e'."
print(wordCount(p))
Python outputs ('Your text contains', 108, 'words, of which', 50, '(', 46.3, '%)', "contains an 'e'.") which is a tuple, not a string.
I know I can just put print at the end of the function and call the function without print() statement, but how do I solve this with a return statement?
It's because you're using commas in your return statement, which Python is interpreting as a tuple. Try using format() instead:
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'".format(wordnum, eWordnum, percent)
>>> wordCount("doodle bugs")
"Your text contains 2 words, of which 1 (0.0%) contains an 'e'"
return "Your text contains {0} words, of which {1} ({2}%) contains an 'e'.".format(wordnum,eWordnum,percent)
return "Your text contains " + str(wordnum) +
" words, of which " + str(eWordnum) +
" (" + str(percent) + "%)" + " contains an 'e'."
or
return "Your text contains %s words, of which %s (%s%%) contains an 'e'."
% (wordnum, eWordnum, percent)
In the first case, you do a string concatenation and you have to convert wordnum, eWordnum and other variables that are numeric ones, into str (by doing str(variableName)) to allow the concatenation (and for haven't runtime error)
In the second case, you do a string replacement that means that you give some kind of "placeholder" %s (that means string) and you replace them with tuple argument that follows the % symbol
If you return something separate by , you'll return a tuple (as you can see)
return "Your text contains %s words, of which %s (%s%%) contains an 'e'." % (wordnum, eWordnum, percent)
A for loop might work, though you would have to format the strings to add spaces to them.
for item in tuplename: print item,
Make sure to keep the comma after item, because that prints it on the same line.
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
eWordnum = len(eWord)
percent = round(eWordnum / wordnum * 100,2)
dummy = "Your text contains {0} words, of which {1} {2} contains an 'e'.".format(wordnum,eWordnum, percent)
return dummy
print(wordCount(p))
try this :
return "Your text contains %(wordnum)s words, of which %(ewordnum)s (%(percent)s %%), contains an 'e'."%locals()
using %(variable_name)s as string formatting is often easier to maintain.
how about this
return "Your text contains " + wordnum + " words, of which " + eWordnum + " (" + percent + "%) " + " contains an 'e'."
replace the commas with "+", this should work.
When I run the code below I get:
Thank you for joining, ['cars', 'gas', 'jewelry']but['bus', 'join'] are not keywords.
How can I effectively turn the lists in to just strings to be printed? I suspect I may need a regular expression... this time :)
import re
pattern = re.compile('[a-z]+', re.IGNORECASE)
text = "join cars jewelry gas bus"
keywordset = set(('cars', 'jewelry', 'gas', 'food', 'van', 'party', 'shoes'))
words = pattern.findall(text.lower())
notkeywords = list(set(words) - keywordset)
keywords = list(keywordset & set(words))
if notkeywords == ['join']:
print "Thank you for joining keywords " + str(keywords) + "!"
else:
print "Thank you for joining, " + str(keywords) + "but" + str(notkeywords) + " are not keywords."
To convert list to strings use str.join like this
print "Thank you for joining keywords " + ",".join(keywords) + "!"
This if notkeywords == ['join']: is not a way to compare list elements.
>>> mylist = [1,2]
>>> mylist == 1
False
you should in operator to check for equality.
>>> mylist = [1,2]
>>> 1 in mylist
True
Just use someString.join(list):
if notkeywords == ['join']:
print "Thank you for joining keywords " + ", ".join(keywords) + "!"
else:
print "Thank you for joining, " + ", ".join(keywords) + "but" + ", ".join(notkeywords) + " are not keywords."
If I understood your question correctly, you'll want to use the .join() string method to combine the list before printing it.
For example:
', '.join(my_list)
will give you comma separated output. ', ' can be whatever kind of separator you like.