>>> 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]]
Related
I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.
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.
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)
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.