Please what function takes a list value as an argument and returns a string with all the items separated by a comma and a space with and inserted before the last item.
I could only think of something a bit hacky.
value_list = [bar, foo, baz]
value_string = str(value_list)
value_string[len(value_list[-1])-1] = " and "
What this does is converting the list to a string and then replacing the last comma with an and since the last comma is located before[-1] the last word value_list[-1]
If "lst" is your list and your values have a str method then the following works (for small inputs).
", ".join(map(str, lst[:-1])) + " and " + str(lst[-1])
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
I just started Automate The Boring Stuff, I'm at chapter 1.
myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + lengthofname)
I ran this, it gave me Can't convert 'int' object to str implicitly.
My reasoning at line 3 is that I want the variable myname to be converted into an integer and then plugged into line 4.
Why would this be an erroneous way of coding?
When you have print ('your name is this many letters:' + lengthofname), python is trying to add an integer to a string (which of course is impossible).
There are 3 ways to resolve this problem.
print ('your name is this many letters:' + str(lengthofname))
print ('your name is this many letters: ', lengthofname)
print ('your name is this many letters: {}'.format(lengthofname))
You have problem because + can add two numbers or concatenate two strings - and you have string + number so you have to convert number to string before you can concatenate two strings - string + str(number)
print('your name is this many letters:' + str(lengthofname))
But you can run print() with many arguments separated with comma - like in other functions - and then Python will automatically convert them to string before print() displays them.
print('your name is this many letters:', lengthofname)
You have only remeber that print will add space between arguments.
(you could say "comma adds space" but print does it.)
Your code seems to be Python 3.x. The following is the corrected code; just convert the lengthofname to string during print.
myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + str(lengthofname))
I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.
You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'
Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())
Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'
Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Author's solution:
def right_justify(s):
print (' '*(70-len(s))+s)
>>> right_justify('allen')
My solution:
def right_justify(s):
space_count=70-len(s)
for i in range(0,space_count,1):
print " ",
print s
strng=raw_input("Enter your desired string:")
print len(strng)
right_justify(strng)
The output of my code is different than the output of author's code: I am getting twice as many spaces, e.g. 130 instead of 65.
But it seems to me that the two pieces of code are logically equivalent. What am I overlooking?
The problem is with your print statement
print " ",
will print two spaces for each iteration of the loop. When terminating the print statement with a comma, subsequent calls will be delimited by a space.
On a side note, another way to define your right_justify function would be
def right_justify(s):
print '%70s' % s
The print " ", line actually prints two spaces (one from the " ", one from the ,). You could replace it with print "", to have your function work identically to the original.
Your code has 130 spaces, the author's code has 65 spaces. This is because
print " ",
...adds a space. What you want is:
print "",
I would prefer the function str.rjust(70," ") which does the trick, I think, like so:
strng.rjust(70," ")
In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.