I have a program that prints out strings from an array like this:
for x in strings
print x,
Which works fine, the strings all print on the same line which is what I want, but then I also have to print out a string that isn't part of the array on a new line. Like this:
for x in strings:
print x,
print second_name
Which ends up all printing on the same line. I want second_name to print on a newline though, how do I do this?
Use the newline character \n:
print '\n' + second_name
I personally think it would be best to use str.join here:
print " ".join(strings)
print second_name
The for-loop just seems like overkill.
The most direct solution is that if you used "print" without final newline in a cycle, add it after this cycle; so the code will look like
for x in strings:
print x,
print ## this terminates the first output line
print second_name
This is kind of the most proper usage of print "API" according to its concepts.
OTOH the answer by K DawG does essentialy the same in other way, putting the default ending '\n' at beginning of the next "print", and, stream nature of stdout makes results of these two variants identical.
NB your construct isn't portable directly to Python3. Python2's print adds a space before each argument unless output isn't at beginning of line. Python3's separator is applied between arguments, but not before the first one in a line. So this manner (cloned from BASIC) isn't perspective and should be replaced with an own manner, like:
out = ''
for x in strings:
out += ' ' + x
print(out[1:])
print(second_name)
but, " ".join(strings) is generally faster and more clear to read.
Related
I am making a poem generator in python, and I am currently working on how poems are outputted to the user. I would like to make it so every line that is outputted will have a comma follow after. I thought I could achieve this easily by using the .join function, but it seems to attach to letters rather than the end of the string stored in the list.
line1[-1]=', '.join(line1[-1])
print(*line1)
print(*line2)
Will output something like:
Moonlight is w, i, n, t, e, r
The waters scent fallen snow
In hindsight, I should have known join was the wrong function to use, but I'm still lost. I tried .append, but as the items in my list are strings, I get the error message "'str' object has no attribute 'append'."
I realize another fix to all this might be something like:
print(*line1, ",")
But I'm working on a function that will decide whether the correct punctuation needs to be "!", ",", "?", or "--", so I am really hoping to find something that can be attached to the string in the list itself, instead of tacked on during the output printing process.
Just use the + or += operator for strings, for example:
trailing_punct = ',' # can be '!', '?', etc.
line1 += trailing_punct
# or
line1 = line1 + trailing_punct
+= can be used to modify the string "in place" (note that under the covers, it does create a new object and assign to it, so id(line1) will have changed after this operation).
It seems your line1 and line2are lists of strings, so I'll start by assuming that:
line1 = ["Moonlight", "is", "winter"]
line2 = ["The", "waters", "scent", "fallen", "snow"]
You are using the default behaviour of the print function when given several string arguments to add the space between words: print(*line1) is equivalent to calling print(line1[0], line1[1], ...) (see *args and **kwargs).
That makes adding the line separator to the list of words of the line insufficient, as it will have a space before it:
print("\n--//--\nUsing print default space between given arguments:")
line_separator = ","
line1.append(line_separator)
print(*line1)
print(*line2)
Results in:
--//--
Using print default space between given arguments:
Moonlight is winter ,
The waters scent fallen snow
What you want to do can be done by joining the list of words into a single string, and then joining the list of lines with the separator you want:
print("\n--//--\nPrinting a single string:")
line1_str = ' '.join(line1)
line2_str = ' '.join(line2)
line_separator = ",\n" # notice the new line \n
lines = line_separator.join([line1_str, line2_str])
print(lines)
Results in
--//--
Printing a single string:
Moonlight is winter,
The waters scent fallen snow
Consider using a list of lines for easier expansion, and maybe a list of separators to be used in order for each line.
I wrote a program in which the user may enter any string. It should:
Delete all the vowels.
Insert the character "." before each consonant.
Replaces all uppercase consonants with corresponding lowercase ones.
Here is the code I wrote:
s=raw_input()
k=s.lower()
listaa=[]
for x in k:
listaa.append(x)
if x=='a':
listaa.remove('a')
if x=='o':
listaa.remove('o')
if x=='y':
listaa.remove('y')
if x=='e':
listaa.remove('e')
if x=='u':
listaa.remove('u')
if x=='i':
listaa.remove('i')
for a in listaa:
print '.%s'%(a),
This code works fine, but for example if I use the input tour, the output is .t .r. Although this is right, it's not exactly what i want. I want to remove spaces between them. I want output that looks like: .t.r
How do I do this?
If you put a comma after a print, it adds a space to the print statement. To not print a space or newline, use sys.stdout.write()
Fixed code:
import sys
s=raw_input()
k=s.lower()
listaa=[]
for x in k:
listaa.append(x)
if x=='a':
listaa.remove('a')
if x=='o':
listaa.remove('o')
if x=='y':
listaa.remove('y')
if x=='e':
listaa.remove('e')
if x=='u':
listaa.remove('u')
if x=='i':
listaa.remove('i')
for a in listaa:
sys.stdout.write('.%s' % a)
Note: you will need to add the import sys statement to use sys.stdout.write
Avoid using remove, since it removes the first occurrence of an item.
Instead, determine what you need to append before appending:
if x in 'bcdfghjklmnpqrstvwxyz':
listaa.append('.')
listaa.append(x)
elif x not in 'aeiou':
# If x is neither a vowel nor a consonant, it is appended.
listaa.append(x)
Also, it would be good to convert your list back to a string at the end:
result = ''.join(listaa)
print result
Regular expressions (contained in the re library) are designed to do exactly this sort of stuff.
import re
import string
alphabet = string.ascii_lowercase
vowels = 'aeiou'
consonants = "".join(set(alphabet)-(set(vowels)))
vowelre = re.compile("["+vowels+"]", re.IGNORECASE)
consonantre = re.compile("(["+consonants+"]){1}", re.IGNORECASE)
text = "Mary had a little lamb The butcher killed it DEAD"
print(vowelre.sub("", text))
print(consonantre.sub(".", text))
I note that you've put the Python 2.7 tag on your query. If you are using 2.7 then I would recommend you get used to using the Python 3 style print function. To enable this you may need a line
from __future__ import print_function
in your code.
tim#merlin:~$ python retest.py
Mry hd lttl lmb Th btchr klld t DD
.a.. .a. a .i...e .a.. ..e .u...e. .i..e. i. .EA.
HTH
using print elem, in python uses the delimiter of a space which means it automatically prints a space after each call to print. this can be avoided by calling print only once by making a single string:
print ''.join(listaa)
str.join(list) is a built in string method that joins a list's elements together with str. the problem with this is that it wont have a period before each consonant.
your logic can also be changed to remove if statements. best way to do this is to change your logic to a add if not in kind of way:
s=raw_input()
k=s.lower()
listaa=[]
for x in k:
if x not in ['a','e','i','o','u']: listaa.append('.'+x.lower())
all this does is check if x is a vowel, if not add a string made up of a period and x
you can also do this all in one line:
print ''.join('.'+x.lower() for x in raw_input() if x not in 'aeiou')
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.
I have this code:
filenames=["file1","FILE2","file3","fiLe4"]
def alignfilenames():
#build a string that can be used to add labels to the R variables.
#format goal: suffixes=c(".fileA",".fileB")
filestring='suffixes=c(".'
for filename in filenames:
filestring=filestring+str(filename)+'",".'
print filestring[:-3]
#now delete the extra characters
filestring=filestring[-1:-4]
filestring=filestring+')'
print "New String"
print str(filestring)
alignfilenames()
I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Any idea what's going on or how to fix it?
Does this do what you want?
>>> filenames=["file1","FILE2","file3","fiLe4"]
>>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames))
>>> c
'suffixes=c(".file1",".FILE2",".file3",".fiLe4")'
Using a string.join is a much better way to add a common delimiter to a list of items. It negates the need to have to check for being on the last item before adding the delimiter, or in your case attempting to strip off the last one added.
Also, you may want to look into List Comprehensions
It looks like you might be trying to use python to write an R script, which can be a quick solution if you don't know how to do it in R. But in this case the R-only solution is actually rather simple:
R> filenames= c("file1","FILE2","file3","fiLe4")
R> suffixes <- paste(".", tolower(filenames), sep="")
R> suffixes
[1] ".file1" ".file2" ".file3" ".file4"
R>
What's going on is that this slicing returns an empty string
filestring=filestring[-1:-4]
Because the end is before the begin. Try the following on the command line:
>>> a = "hello world"
>>> a[-1:-4]
''
The solution is to instead do
filestring=filestring[:-4]+filestring[-1:]
But I think what you actually wanted was to just drop the last three characters.
filestring=filestring[:-3]
The better solution is to use the join method of strings as sberry2A suggested