Printing multiple newlines with Python - python

I'm trying to separate some outputted text in Python 3.
Heres sorta an example of what iv got now
print("words")
print("")
print("")
print("")
print("")
print("")
print("")
#(Print would keep going on like 50 times)...
print("more words")
now putting all those prints is annoying and i need the words to be vertically seperated. like this
words
more words
Any ideas on how to separate huge verticle distances.
Thanks :)

You can construct a string of newline characters, which will result in vertical space, like this:
lines = 5 # Number of blank lines
print("\n" * lines)

You could put a newline character "\n" in the string, e.g.
>>> print ("\n\n\n\n")
Characters preceded by a backslash are 'escaped', and are converted to special characters by Python. Some commonly used escape sequences are:
Newline "\n"
Tab "\t"
Carriage Return "\r"
Backslash "\\"
Hexadecimal character code "\x0f"
Quote character "\"" or '\''
Note that strings can be repeated by multiplying them with a number, e.g.
>>> print ("\n" * 100)

Related

Swap last two characters in a string, make it lowercase, and add a space

I'm trying to take the last two letters of a string, swap them, make them lowercase, and leave a space in the middle. For some reason the output gives me white space before the word.
For example if input was APPLE then the out put should be e l
It would be nice to also be nice to ignore non string characters so if the word was App3e then the output would be e p
def last_Letters(word):
last_two = word[-2:]
swap = last_two[-1:] + last_two[:1]
for i in swap:
if i.isupper():
swap = swap.lower()
return swap[0]+ " " +swap[1]
word = input(" ")
print(last_Letters(word))
You can try with the following function:
import re
def last_Letters(word):
letters = re.sub(r'\d', '', word)
if len(letters) > 1:
return letters[-1].lower() + ' ' + letters[-2].lower()
return None
It follows these steps:
removes all the digits
if there are at least two characters:
lowers every character
builds the required string by concatenation of the nth letter, a space and the nth-1 letter
and returns the string
returns "None"
Since I said there was a simpler way, here's what I would write:
text = input()
result = ' '.join(reversed([ch.lower() for ch in text if ch.isalpha()][-2:]))
print(result)
How this works:
[ch.lower() for ch in text] creates a list of lowercase characters from some iterable text
adding if ch.isalpha() filters out anything that isn't an alphabetical character
adding [-2:] selects the last two from the preceding sequence
and reversed() takes the sequence and returns an iterable with the elements in reverse
' '.join(some_iterable) will join the characters in the iterable together with spaces in between.
So, result is set to be the last two characters of all of the alphabetical characters in text, in reverse order, separated by a space.
Part of what makes Python so powerful and popular, is that once you learn to read the syntax, the code very naturally tells you exactly what it is doing. If you read out the statement, it is self-describing.

newline charachter use in typecasting

so i just started learning python so please be humble i am still a noob so this is my code
x="hello world"
y=45
z=45.7
w=65
v="harry"
print(y+z)
print(y+w)
print(x+v)
print(type(x))
print(type(y))
print(type(z))
#read explanation from notes
#lets start with typecasting
m="52"
n="34"
print(m+n)
print(int(m)+int(n))
print(float(m)+float(n))
#this code is for conversion into different types
x=5
print(x*"hello world \n")
print(x*"hello world")
print(x*str(int(m)+int(n)))
here in the last statement i tried to print it with a new line character like this
print(X*str(int(m)+int(n)\n))
and this input returned an error like this
print(x*str(int(m)+int(n))\n)
^
SyntaxError: unexpected character after line continuation character
i tried inserting the newline character here and there but it did not work how do i make it print in new lines using new line character
You need to use + to concatenate strings. You also have to put \n inside quotes. And add parentheses to specify the grouping, since * has higher precedence than +.
print(x * (str(int(m) + int(n)) + "\n"))
You can also simplify this by using a format string.
print(x * f'{int(m)+int(n)}\n')
To use the newline character you have to surround it with quotation marks like this "\n" or '\n'. Otherwise it won't be interpreted as a string.
So your command could look like this print((x*str(int(m)+int(n)))+"\n") if you want to print the newline once or like this print(x*(str(int(m)+int(n))"\n")) if you need a newline after each (str(int(m)+int(n).

first symbol not printing but the rest is normally printing

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.

Deleting certain characters from a string

I try to figure out how I can delete certain characters from a string. Unfortunately, it doesn't work. I would appreciate all the help.
def delete_char(string):
string = list(string)
string.remove("\n")
return ''.join(string)
delete_char("I want \n to test \n if you \n work")
How about using replace, instead?
def delete_char(string, target_char, replacement_char=""):
return string.replace(target_char, replacement_char)
print(delete_char("I want \n to test \n if you \n work", "\n"))
You need to re-assign the string value to the removed form. Additionally I would suggest using replace instead of remove in this place, and replacing it with an empty character. Something like this should work:
def delete_char(string):
string = string.replace("\n", "")
return string
You could use str.split and str.join:
>>> ' '.join("I want \n to test \n if you \n work".split())
I want to test if you work
This isn't the same as just removing the newline character but it will ensure only one space between words.
Otherwise just replace the newline with nothing:
>>> "I want \n to test \n if you \n work".replace('\n', '')
I want to test if you work

How do I trim a string after certain amount of characters appear more then once in Python?

I am trying to scan a string and every time it reads a certain character 3 times, I would like to cut the remaining string
for example:
The string "C:\Temp\Test\Documents\Test.doc" would turn into "C:\Temp\Test\"
Every time the string hits "\" 3 times it should trim the string
here is my code that I am working on
prefix = ["" for x in range(size)]
num = 0
...
...
for char in os.path.realpath(src):
for x in prefix:
x = char
if x =='\': # I get an error here
num = num + 1
if num == 3:
break
print (num)
print(prefix)
...
...
the os.path.realpath(src) is the string with with the filepath. The "prefix" variable is the string array that I want to store the trimmed string.
Please let me know what I need to fix or if there is a simpler way to perform this.
Do split and then slice list to grab required and join:
s = 'C:\Temp\Test\Documents\Test.doc'
print('\\'.join(s.split('\\')[:3]) + '\\')
# C:\Temp\Test\
Note that \ (backslash) is an escaping character. To specifically mean a backslash, force it to be a backslash by adding a backslash before backslash \\, thereby removing the special meaning of backslash.
In python the backslash character is used as an escape character. If you do \n it does a newline, \t does a tab. There are many other things such as \" lets you do a quote in a string. If you want a regular backslash you should do "\\"
try
s = "C:\\Temp\\Test\\Documents\\Test.doc"
answer = '\\'.join(s.split('\\', 3)[:3])
Something like this would do..
x = "C:\Temp\Test\Documents\Test.doc"
print('\\'.join(x.split("\\")[:3])+"\\")

Categories

Resources