I have been trying to remove the first two commas of a print statement and am having trouble doing this.
The print statement essentially allows to print the elements of a set without the brackets (using *) and with commas separating the elements (using sep=", ").
Only problem is the first two pieces of the statement (a cross mark and a sentence) also get separated with a comma. This is not desired (as shown in screenshot).
I would like to know how I can remove the comma after the cross mark and the comma after the colon.
FYI: '\033[91m' = red font colour, '\u274C' = cross mark, '\033[0m' = no color
My code is shown below.
print('\033[91m' + '\u274C', "Paragraphs contain unspecified font(s):" + '\033[0m', *invalid_font, sep=", ")
You can either, use two separate print statements.
print('\033[91m\u274C '
'Paragraphs contain unspecified font(s):'
'\033[0m', end='')
print(*invalid_font, sep=", ")
or join the fonts with comma and space.
print('\033[91m\u274C '
'Paragraphs contain unspecified font(s):'
'\033[0m',
', '.join(map(str, invalid_font)))
Edit
As #S3DEV pointed out in the comments, it is unnecessary to map the invalid_font iterable to str if it is already an iterable of str. In this case, you just need
print('\033[91m\u274C '
'Paragraphs contain unspecified font(s):'
'\033[0m',
', '.join(invalid_font))
Related
I have a list gathered from a text file, f, named fList. I want to print each item in list separately on a new line and I used the following.
f.seek(0)
fList = f.readlines()
items = fList[::2] #Every other value
print("\n Catalogue Items: \n")
print(*items)
When printing in the console, the first item always has a weird spacing. Image of output in console
The first item always does not follow the spacing of the rest when printed.
Your text appears to include carriage return characters.
Printing *items only adds the spaces between elements, not the carriage returns, or a space before the first item.
Assuming you want those carriage returns, just add a space to the print statement (to add a space before the first element too), or use join to avoid adding the spaces between elements.
print(''.join(items)) # no spaces
Or...
print('', *items) # consistent single spaces
Or...
print(' ', ' '.join(items)) # consist double spaces
Try using the var.strip() function, it gets rid of spaces on both sides
Genre = str(input(prompt))
GenreStripped = Genre.strip()
Length = len(GenreStripped)
while Length > 0:
Im trying to make a function that does not only accept ' ' spaces as an input, what are some other python functions to deal with ' ' as an input, because the strip() function does not strip ' '.
.strip() only removes leading and trailing whitespace, not spaces in between characters. you could use .replace(" ", "") instead if you wanted to remove every space
Try running the following to get a sense of the differences between these methods:
print(" test test test ".replace(" ", "")) # 'testtesttest'
print(" test test test ".strip()) # 'test test test'
I am not sure why the first asterisk is not printing, does anyone have any ideas? BTW I am using a dictionary.
input
error
output
' ****'
expected output
'*****'
MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..'}
def encode_Morse(my_msg):
my_msg_Morse=" "
for letter in my_msg:
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+="*"
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
else:
my_msg_Morse+=" "
my_msg_Morse = my_msg_Morse[:-1]
return my_msg_Morse
The problem is that you are not returning the full string and that the last asterisk is not printing. You can fix this problem by amending the assignment my_msg_Morse = my_msg_Morse[:-1]
to
my_msg_Morse = my_msg_Morse.
If you weren't adding blank spaces with this condition (for the characters matched by your dictionary - i.e. the capital letters)
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
it would be more clear that you have this problem generally. Consider the test case where you don't add blanks:
Input:
ERROR
Expected Output:
..-..-.---.-.
Actual Output:
..-..-.---.-
However, you are adding blank spaces after each rendering of a capital into morse code. So this loss of the final character (a blank space) is mostly unobserved.
I don't know what your requirements are but if they are satisfied by returning a string with no trailing white space you could return my_msg_Morse.rstrip(). The rstrip() method of the string object removes all trailing white space. This way, you could preserve your within-string white space while eliminating trailing white space. I also like Tim Robert's suggestion (in a comment to your original question) of using a list and joining it.
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'm working on strings where I'm taking input from the command line. For example, with this input:
format driveName "datahere"
when I go string.split(), it comes out as:
>>> input.split()
['format, 'driveName', '"datahere"']
which is what I want.
However, when I specify it to be string.split(" ", 2), I get:
>>> input.split(' ', 2)
['format\n, 'driveName\n', '"datahere"']
Does anyone know why and how I can resolve this? I thought it could be because I'm creating it on Windows and running on Unix, but the same problem occurs when I use nano in unix.
The third argument (data) could contain newlines, so I'm cautious not to use a sweeping newline remover.
Default separator in split() is all whitespace which includes newlines \n and spaces.
Here is what the docs on split say:
str.split([sep[, maxsplit]])
If sep is not specified or is None, a different splitting algorithm is
applied: runs of consecutive whitespace are regarded as a single
separator, and the result will contain no empty strings at the start
or end if the string has leading or trailing whitespace.
When you define a new sep it only uses that separator to split the strings.
Use None to get the default whitespace splitting behaviour with a limit:
input.split(None, 2)
This leaves the whitespace at the end of input() untouched.
Or you could strip the values afterwards; this removes whitespace from the start and end, not the middle, of each resulting string, just like input.split() would:
[v.strip() for v in input.split(' ', 2)]
The default str.split targets a number of "whitespace characters", including also tabs and others. If you do str.split(' '), you tell it to split only on ' ' (a space). You can get the default behavior by specifying None, as in str.split(None, 2).
There may be a better way of doing this, depending on what your actual use-case is (your example does not replicate the problem...). As your example output implies newlines as separators, you should consider splitting on them explicitly.
inp = """
format
driveName
datahere
datathere
"""
inp.strip().split('\n', 2)
# ['format', 'driveName', 'datahere\ndatathere']
This allows you to have spaces (and tabs etc) in the first and second item as well.