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: ')'
)
Related
Say I have a file called input.txt that looks like this
I listened to 4 u2 albums today
meet me at 5
squad 4ever
I want to filter out the numbers that are on their own, so "4" and "5" should go but "u2" and "4ever" should remain the same. i.e the output should be
I listened to u2 albums today
meet me at
squad 4ever
I've been trying to use this code
for line in fileinput.input("input.txt", inplace=True):
new_s = ""
for word in line.split(' '):
if not all(char.isdigit() for char in word):
new_s += word
new_s += ' '
print(new_s, end='')
Which is pretty similar to the code I found here: Removing numbers mixed with letters from string
But instead of the wanted output I get
I listened to u2 albums today
meet me at 5
squad 4ever
As you can see there are two problems here, first only the first line loses the digit I want it to lose, "5" is still present in the second line. The second problem is the extra white space at the beginning of a new line.
I've been playing around with the code for a while and browsing stackoverflow, but can't find where the problem is coming from. Any insights?
str.split(' ') does not remove the trailing newlines from each line. They end up attached to the last word of the line. So for your first problem, the '5' doesn't get removed because it's actually '5\n', and the \n is not a digit.
The second problem is related. When you print the last word of each line, it contains that newline, plus you're adding a space on to the end. That space shows up as the first character of the next line.
The simplest solution is simply to change line.split(' ') to line.split(). Without any arguments, split() will remove all whitespace, including the newlines. You'll also need to remove the end='' from your print so that the newlines are added back in.
Just use regexp.
re.sub(r"\b\d+\b", "", input)
match any digit between word boundaries
Or to avoid double spaces:
re.sub(r"\s\d+\s", " ", input)
You can use regex:
data = open('file.txt').read()
import re
data = re.sub('(?<=\s)\d+(?=$)|(?<=^)\d+(?<=\s)|(\s\d+\s)', '', data)
Output:
I listened tou2 albums today
meet me at
squad 4ever
Hi I am parsing through XML files grabbing SQL text and paraments. I need to pull the strings that lie between two # signs. For example if this is my text:
CASE WHEN TRIM (NVL (a.SPLR_RMRK, ' ')) = '' OR TRIM (NVL (a.SPLR_RMRK, ' ')) IS NULL THEN '~' ELSE a.SPLR_RMRK END AS TXT_DESCR_J, 'PO' AS TXT_TYP_CD_J FROM #ps_RDW_Conn.jp_RDW_SCHEMA_NAME#.P_PO_RCPT_DTL a, (SELECT PO_RCPT_DTL_KEY, ETL_CRT_DTM FROM #ps_RDW_Conn.jp_RDW_SCHEMA_NAME#.#jp_PoRcptDtl_Src# WHERE ETL_UPDT_DTM > TO_DATE ('#jp_EtlPrcsDt#', 'YYYY-MM-DD:HH24:MI:SS'))
I want to have ps_RDW_Conn.jp_RDW_SCHEMA_NAME, ps_RDW_Conn.jp_RDW_SCHEMA_NAME jp_PoRcptDtl_Src and jp_EtlPrcsDt print out.
Some code that I have so far is
for eachLine in testFile:
print re.findall('#(*?)#', eachLine)
This gives me the following error:
nothing to repeat.
Any help or suggestions is greatly appreciated!
Unlike in bash regular expressions, the * is not a wild-card character, but instead it says repeat 0 or more times the thing before me.
In your regular expression, your * had no symbol to modify and so you saw the complaint nothing to repeat.
On the other hand, if you supply a . symbol for * to modify, testing with one line as an example,
eachLine = '#ps_RDW_Conn.jp_RDW_SCHEMA_NAME#.P_PO_RCPT_DTL a, (SELECT PO_RCPT_DTL_KEY, '
re.findall('#(.*?)#', eachLine)
We get,
['ps_RDW_Conn.jp_RDW_SCHEMA_NAME']
Some more detail.
I'm not sure if this is what you intended, but your *? is actually well placed.
*? is interpreted as a single qualifier which says repeat 0 or more times the thing before me, but take as little as possible.
So this ends up having the similar effect of what #tobias_k suggests in the comments, in preventing multiple groups from being absorbed into one.
>>> line = 'And here is # some interesting code #, where later on there are #fruit flies# ?'
>>> re.findall('#(.*)#', line)
[' some interesting code #, where later on there are #fruit flies']
>>>
>>> re.findall('#(.*?)#', line)
[' some interesting code ', 'fruit flies']
>>>
For reference, browse Repeating Things in docs.python.org
Your regex is not working as intended because you are using both * (0 or more) and ? (0 or 1) to modify the thing before it, but a) there is nothing before it, and b) you should use either * or ?, not both.
If you mean to capture ## or #anything#, then use the regex #(.*)#.
Try to escape ( and ). r'\(.*?\)' should work.
for eachLine in testFile:
print re.findall(r'\(.*?\)', eachLine)
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 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 '