Printing string with multiple placeholder formatters in Python 2.7 - python

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)

Related

Beginner Python - Printing Values in a List

I am new to Python, and I am making a list. I want to make a print statement that says "Hello" to all the values in the lists all at once.
Objects=["Calculator", "Pencil", "Eraser"]
print("Hello " + Objects[0] + ", " + Objects[1] + ", " + Objects[2])
Above, I am repeating "Objects" and its index three times. Is there any way that I can simply write "Objects" followed by the positions of the values once but still get all three values printed at the same time?
Thanks
You could use join() here:
Objects = ["Calculator", "Pencil", "Eraser"]
print('Hello ' + ', '.join(Objects))
This prints:
Hello Calculator, Pencil, Eraser
You can use the string join function, which will take a list and join all the elements up with a specified separator:
", ".join(['a', 'b', 'c']) # gives "a, b, c"
You should also start to prefer f-strings in Python as it makes you code more succinct and "cleaner" (IMNSHO):
Objects = ["Calculator", "Pencil", "Eraser"]
print(f"Hello {', '.join(Objects)}")
Not sure this is the most elegant way but it works:
strTemp = ""
for i in range(len(Objects)):
strTemp += Objects[i] + " "
print ("Hello " + strTemp)
Start with an empty string, put all the values in your list in that string and then just print a the string Hello with your Temporary String like above.

When using python 3.x, how do I take outputs from a "for" command and add them to a list or string?

How would I take the results from the following code and assign a variable to it?
for I in word: print (I + 117)
For example, if the results came out to be 100,101,102,103 how would I get a variable set to "100,101,102,103" without manually entering every number into a variable. Also, I know that it says "your encrypted string is" and I know that that's not really encrypted, but I just got into this so I was just playing around.
word = eval(input("What would you like to say"))
print (word)
encrypt = 117
print ("Your encrypted string is:")
for I in word:
print (I + 117)
assuming I have ASCII codes set to their appropriate values
Thanks to many people (most notably yukashima huksay and ZYYYY) I have my final code here:
word = eval(input("What would you like to say"))
print (word)
changedword = (', '.join(str(I + 15) for I in word))
print ("Your encrypted string is:" + changedword)
Assuming all ASCII codes set as variables.
You should do this:
a = ','.join([x for x in word])
Please note that you can use any string instead of ',' for example ', ' or '\n' or basically whatever you can store in a string.
You can also put a function of x instead like [foo(x) for x in word] or (2*x + 1)
And finally you can also use in-line if/else statements like:
[foo(x) if x>1 else bar(x) for x in word]
And also:
[foo(x) for x in word if x is not None]
The error you are getting is because you are adding a number to a character perhaps what you want to do is:
word = 'mokhlesim'
shift = 117
print(','.join([chr(ord(x)+shift) for x in word]))
result: è,Ö,á,Ö,â
str.join(iterable) would give you what you want.
I don't think eval() is a good practice here. word = input("somethin") is enough for python3.
Also you may want to know about list comprehensions which makes code more concise.
eval(exp) is to use to parse and evaluate exp as a python expression. For example
x = 1
a = eval("x + 1")
print(a)
#should print 2
I think you may want something like
word = input("give me something\n")
a = ','.join([chr(ord(c) + 117) for c in word])
print(a)
#if i type in here, it should print "Ý,Ú,ç,Ú"

How do I put a space between two string items in Python

>>> item1="eggs"
>>> item2="sandwich"
>>> print(item1+item2)
>>> Output: eggssandwich
My main goal is to put a space between eggs and sandwich.
But i'm unsure on how to. Any help would be appreciated
Use .join():
print(" ".join([item1, item2]))
The default for print, however, is to put a space between arguments, so you could also do:
print(item1, item2)
Another way would be to use string formatting:
print("{} {}".format(item1, item2))
Or the old way:
print("%s %s" % (item1, item2))
Simply!
'{} {}'.format(item1, item2) # the most prefereable
or
'%s %s' % (item1, item2)
or if it is just print
print(item1, item2)
for dynamic count of elements you can use join(like in another answer in the tread).
Also you can read how to make really flexible formatting using format language from the first variant in official documentation:
https://docs.python.org/2/library/string.html#custom-string-formatting
Update:
since f-strings were introduced in Python 3.6, it is also possible to use them:
f'{item1} {item2}'
Just add the space!
print(item1 + ' ' + item2)
# works every time
print(item1, item2)
# Only works if items 1 & 2 are strings.
print(item1 + " " + item2)
Here are three easy solutions to add a space.
Add a space in between, but as noted above this only works if both items are strings.
print("eggs" + " " + "sandwich")
Another simple solution would be to add a space to end of eggs or beginning of sandwich.
print("eggs " + "sandwich")
print("eggs" + " sandwich")
These will all return the same result.
There are a lot of ways ;) :
print(f'Hello {firstname} {lastname}')
Or
print("Hello", firstname, lastname)
Or
print("Hello", firstname + ' ' + lastname)
Or
print(' '.join(["Hello", firstname , lastname]))
Or
[print(i, end=' ') for i in ["Hello", firstname, lastname]]

error defining a string

I am trying to make a program that adds a number to a string and prints it. Here is my code:
n1 = 5
n2 = 6
statement = "number 1: ",n1,") (number 2: ",n2,")"
print(statement)
I want it to print (number1: 5 ) * (number2: 6 ).
EDIT:
The problem I had was my items were separated by commas, not plus signs. This caused an error becuase you need to seperate things with plus signs.
3 ways to get around this would be:
A:% formatting
number = 1
statement = "Your number is %s." % (number)
B:{} formatting
number = 2
statement = "Your number is {}.".format(number)
C:Converting to a string
number = 3
statement = "Your number is "+str(number) + "."
You are trying to join strings using the comma operator. This creates a tuple, not a string. Strings are concatenated using the + operator, like so:
statement = "(x +" + str(n1) + ") * (x +" + str(n2) + ")"
But it would be even easier to use the string formatting operators:
statement = "(x + {}) * (x + {})".format(n1,n2)
or
statement = "(x + %s) * (x + %s)" % (n1, n2)
Your syntax in line 4, where you build the statement, is one that constructs a list from comma-separated elements. You need to convert the integers to strings somehow, and work in the spaces you want. Here's the closest equivalent, I think:
statement = "(x + " + str(n1) + " ) * (x + " + str(n2) + " )"
This prints the output you requested.
When you construct your "statement" variable, you are building a tuple, not a string (those commas are the culprit).
Build that variable as a string, and you'll be able to add it to the other string.
statement = "(x + {n1}) * x +{n2})".format(n1=n1, n2=n2)

Python: turning a tuple from return statement into a string

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.

Categories

Resources