print a string in python left justified with an offset - python

I am using Python 2.4. I would like to print a string left justified but with an "offset". By that I mean, print a string with a set number of spaces before it.
Example:
Print string "Hello" in a space of width 20, left justified, but five spaces inserted before the string.
" Hello " #(The string has 5 spaces prior, and 10 space after)
print "Hello".ljust(20) #does not cut it.
I could use the following as a workaround:
print " ", "Hello".ljust(15)
Is there a better approach than printing a string of 5 spaces.
Thank you,
Ahmed.

Not really.
>>> ' %-15s' % ('Hello',)
' Hello '

Related

How to remove whitespaces in a string except from between certain elements

I have a string similar to (the below one is simplified):
" word= {his or her} whatever "
I want to delete every whitespace except between {}, so that my modified string will be:
"word={his or her}whatever"
lstrip or rstrip doesn't work of course. If I delete all whitespaces the whitespaces between {} are deleted as well. I tried to look up solutions for limiting the replace function to certain areas but even if I found out it I haven't been able to implement it. There are some stuff with regex (I am not sure if they are relevant here) but I haven't been able to understand them.
EDIT: If I wanted to except the area between, say {} and "", that is:
if I wanted to turn this string:
" word= {his or her} and "his or her" whatever "
into this:
"word={his or her}and"his or her"whatever"
What would I change
re.sub(r'\s+(?![^{]*})', '', list_name) into?
See instead going arround re you can replace uisng string.replace. Which will be much more easier and less complex when you playing around strings. Espacillay when you have multiple substitutions you end up bigger regex.
st =" word= {his or her} whatever "
st2=""" word= {his or her} and "his or her" whatever """
new = " ".join(st2.split())
new = new.replace("= ", "=").replace("} ", "}").replace('" ' , '"').replace(' "' , '"')
print(new)
Some outputs
Example 1 output
word={his or her}whatever
Example 2 output
word={his or her}and"his or her"whatever
You can use by replace
def remove(string):
return string.replace(" ", "")
string = 'hell o whatever'
print(remove(string)) // Output: hellowhatever

difference between print(" str", a ) and print("str" + a )

I am a beginner with python3 and I use a lot print or the logging module to follow the code on the console. A simple example below: what's the difference between:
number = "seven"
print("I cooked " , number , " dishes")
and
number = "seven"
print("I cooked " + number + " dishes")
Internally the difference is that this example (no + sign):
number = "seven"
print("I cooked " , number , " dishes")
Is printing 3 separate string objects. "I cooked ", is object 1, number is object 2, and " dishes" is object 3. So this has 3 objects total.
In the second example (with the + sign):
number = "seven"
print("I cooked " + number + " dishes")
the 3 separate strings are first being concatted into 1 new string object before being printed to stdout. So this example has 4 objects total.
The print statement supports multiple ways of parsing values.
number = 'seven'
Examples: Different style of adding argument in print statement
print("I cooked " , number , " dishes")
C-Style formatting (old):
print("I cooked %s dishes" % number)
C-Style formatting (new) using fomat:
print("I cooked {} dishes ".format(number))
f-string style
print(f"I cooked {number} dishes")
String concatenating:
print("I cooked " + number + " dishes")
You don't necessary to stick with one style. You have various options of doing the same.
The operator + can be only used on strings.
The operator , can be used on any type, and adds a space before automatically.
In addition, + can be used not only in printing but to add one string to another while , cant.
(Note that in the two examples you have, by simply running them will show that the results are different, as the first one will have some words separated by double spaces.)
The print() function will take in strings, each string will be printed out with a ' ' between them:
print('hello', 'world')
Output:
hello world
That is because of the keyword argument, sep. By default, sep=' ', that is changeable by simply adding:
print('hello', 'world', sep='\n')
Output:
hello
world
The + operator will not add any separator, it will simply concatenate the strings:
print('hello' + 'world')
Output:
helloworld
As per PEP3105 print is considered as a function taking *args (several positional arguments).
To answer your question, the result is the same; however, your implementation is different. In the first case you give print multiple arguments to print, while in the second case you give print a concatenated string that you would like to print.
when using
number = "seven"
print("I cooked " , number , " dishes")
print gets 3 different objects (3 strings) as arguments, converts them to string and then prints.
However using
number = "seven"
print("I cooked " + number + " dishes")
means that first these three strings are concatenated and then passed as one object to print.
In reality, it means, that if you do for example
print('xxx' + 5 + 'yyy')
it will throw and error, as it is not possible to directly concatenate string and int types.
Also note following example:
#concatenating 3 strings and passing them as one argument to print
>>> print('xxx' + 'a' + 'yyy',sep=',')
xxxayyy
#passing 3 strings as 3 arguments to print
>>> print('xxx','a','yyy',sep=',')
xxx,a,yyy
You can notice, that in first example, although sep is used (thus it should separate 3 strigns with given separator) it does not work, because these strings are concatenated first and then passed as one argument to print. In the second example however, strings are passed as separated arguments, therefore sep=',' works, because print just knows that it should pass the separator between each given string.
Lets say a = "how are you" and b = "goodbye" which are 2 string variables.
If we do print(a, b):
The statement will print first a then b as separate strings outputted on one line:
Output:
> how are you goodbye
If we do print(a + b) the statement will concatenate these two variables a and b together:
Output:
> how are yougoodbye
(here there's no spacing due no white spacing in the print statement or the variables)

Why is this not a string?

I'm working my way through "Automate the Boring Stuff with Python" by Al Sweigart (great read so far!).
Could someone kindly explain this line of code to me:
print('Jimmy Five Times (' + str(i) + ')')
So this line is used in a while loop and results in the following being printed:
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
Thats great but reading the code I would have expected this to print just once:
Jimmy Five Times ( + str(i) + )
Why are the contents of the bracket not converted to a string when the code in question is encapsulated by ' ' ? Whats more, the nested brackets also convert to a string, which I would expect to happen, but clearly its function appears to be to evaluate its contents first...and I figured it out. I'm going to leave this up here in case anyone else is wondering:
Print(
First string: 'Jimmy Five Times ('
+ str(i) +
Second string: ')'
)
It is a simple string addition :
second_string = 'second string'
print ('first string'+str(second_string)+'third string as a bracket'
in your case:
first string is: 'Jimmy Five Times ('
second string is: str(i)
and third string is: ')'
Since Python 3.6 implement f-string we should use cleaner and easier to read version:
print (f'Jimmy Five Times ({i})')
To print the same you could also do:
print('Jimmy Five Times ({})'.format(str(i)))
#or
print(f'Jimmy Five Times ({str(i)})')
Whatever code is inside the curly brackets will be executed and inserted into the string, however, it's important not to forget the f"{}" at the start, otherwise this won't work
I was reading the quotation marks incorrectly. Below shows the first and second block of quotes which results in the correct code executing as shown in the book:
Print(
First string: 'Jimmy Five Times ('
+ str(i) +
Second string: ')'
)

Printing multiple newlines with 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)

How to print spaces in Python?

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.

Categories

Resources