Beginner looking for help for printing in python - python

print ("ln(x) at " ,x "is: " ,lnx)
I keep getting syntax error on the last quotation mark in there.
No matter what kind of print statements I do, it seems it does not let me put multiple quotation marks in the same print. Am I doing this wrong?

You're missing a comma:
print ("ln(x) at ", x, "is: ", lnx)

You are much better of shifting into the new print format style:
print('ln(x) at {} is: {}'.format(x, lnx))
Using this form gives you access to the Format Specification Mini-Language, which allows you specify widths, number of decimals to print, and much more.
Most likely the following would look better where I print the logarithm with 4 decimals:
print('ln({}) = {:,.4f}'.format(x, lnx)
Note that if you want to include the quotation marks, you either need to escape it or switch the outer quotation to the other set. Say you want to print Billy "Bobby" Thornton these two ways could do that:
print('Billy "Bobby" Thornton')
print("Billy \"Bobby\" Thornthon")

Related

Python read strings from file, preserving variables to be printed

I am making a Python script that will choose a response at random from a list.
To fill this list I want to read strings from a file, the strings will look something like this:
"This number is " + str(num) + ", this is good"
"Oh no the number is " + str(num) +", this is good
Obviously these are read from the file as strings so if I printed one of them they would come out as you see them here and wont have the value for "num" substituted. Is there anyway to read these strings from a file while keeping the ability to substitute variables (like a raw format) like how it would work if my code did
list.append("This number is " + str(num) + ", this is good")
The reason I want to read from a file is because I will have many different strings and they may change so I would rather not hard code them into the program (keep in mind the example strings are very basic)
Thanks
You could use the format specification mini-language, and then call .format on your strings before displaying them.
strings.txt:
This number is {num} this is good
Oh no the number is {num} this is good
main.py:
import random
with open("strings.txt") as file:
possible_strings = file.read().split("\n")
number = 23
s = random.choice(possible_strings)
print(s.format(num=number))
Possible output:
This number is 23 this is good
Use something in your file to indicate a substitution is needed, and then make those substitutions.
For example, if you need to put in the value of num, your text could use {{num}} where the substitution is needed. Then use regex to find such substrings, and replace them with the desired values.

Python - \n appearing in concatenated strings

I've been having an issue with my Python code. I am trying to concatenate the value of two string objects, but when I run the code it keeps printing a '\n' between the two strings.
My code:
while i < len(valList):
curVal = valList[i]
print(curVal)
markupConstant = 'markup.txt'
markupFileName = curVal + markupConstant
markupFile = open(markupFileName)
Now when I run this, it gives me this error:
OSError: [Errno 22] Invalid argument: 'cornWhiteTrimmed\nmarkup.txt'
See that \n between the two strings? I've dissected the code a bit by printing each string individually, and neither one contains a \n on its own. Any ideas as to what I'm doing wrong?
Thanks in advance!
The concatenation itself doesn't add the \n for sure. valList is probably the result of calling readlines() on a file object, so each element in it will have a trailing \n. Call strip on each element before using it:
while i < len(valList):
curVal = valList[i].strip()
print(curVal)
markupConstant = 'markup.txt'
markupFileName = curVal + markupConstant
markupFile = open(markupFileName)
The reason you are not seeing the \n when you actually print out the python statements is because \n is technically the newline character. You will not see this when you actually print, it will only skip to a new line. The problem is when you have this in the middle of your two strings, it is going to cause problems. The solution to your issue is the strip method. You can read into its documentation here (https://www.tutorialspoint.com/python/string_strip.htm) but basically you can use this method to strip the newline character off of any of your strings.
Just to make an addition to the other answers explaining why this came about:
When you need to actually inspect what characters a string contains, you can't simply print it. Many characters are "invisible" when printed.
Turn the string into a list first:
list(curVal)
Or my personal favorite:
[c for c in curVal]
These will create lists that properly show all hard to see characters.

Python Format Best Practices

I'm just coming up to speed with Python and had a question about best practices (or at least common practices) around using .format on a string.
My question is mostly around when you would use blank curly brackets vs. an index number vs. a name.
For example if you had a single variable that you wanted to include in a string which one would you do?
print "I {} Stack Overflow".format(var)
print "I {0} Stack Overflow".format(var)
print "I {verb} Stack Overflow".format(verb = var)
Does this change if you have multiple variables you want to include? Maybe it's OK to include {} for a single var, but never for multiple vars?
Any thoughts or insights here would be greatly appreciated.
Thanks!
I don't think there are (yet) any practices established as "best" or even as "common", so you'll get a bunch of opinions (including mine:-).
I think that {named} curlies are the way to go when your format string is a variable (e.g coming from a database or config file, picked depending on user's chosen language, etc, etc) because they let you pick and choose which of the (named) arguments to format, the order, possibly repeat them, and so forth, while staying readable.
If the format string is a literal, empty curlies a la {} are least obtrusive and thus may end up most readable -- unless your format string has "too many" of them, which of course is a style judgment.
At least it's a style issue very cognate to the one you face every time you define or call a function -- how any positional arguments or parameters are "too many" for readability, should you go whole hogs to named parameters and arguments only, etc, etc. Similar considerations apply!
print " I {} Stack Overflow.".format(var) is the correct way.
If you need multiple variable you would just place more curly brackets and add the var names separated by a comma.
print "I {} Stack Overflow. It is a great {} {}!".format(var, var1, var3)
I know this is an old question, but Python 3.6 brings a very cool string format, called "f-strings". It's similar to Javascript. Here is an simple example:
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
It only works in Python 3.6 and above, but I think it's the easiest and more readable way to format strings in Python.
It's ok to use empty braces for one or two variables. I would recommend using named replacement:
for more variables
in situations where replaced string is hard to read
when injected var is repeated.

Python print skip arguments

I have this dirty short line of code printing a formatted date:
print '%f %d' % math.modf(time.time())
Now the modf method gives back two arguments, so the print function expects both. In the sake of purely doing this, and not the simple alternative of putting the output separately in a variable; is there any existing way of excepting parameters in print or is there any way to call specific argument-indexes?
For example I have 3 arguments in a print:
print '%s %d.%f' % 'Money',19,.99
I want to skip the first String-parameter that is parsed. Is there any way to do this?
This is mainly a want-to-know-if-possible question, no need to give alternative solutions :P.
Not in "old school" string formatting.
But the format method of strings does have this ability.
print "{1}".format ("1","2")
The above will skip the "1" and will only print "2".
I hope you don't mind I gave an alternative despite you not asking for it :)

Python- ArcMap - Calculate Fields

I am python newbie and I am trying to count the number of words in a column (Name) in ArcMap by using
!NAME!.count(' ') +
1
but I run into problems with strings like :
First N' Infant Care Center "Baby World"
type.exceptions.Syntaxerror,
even if I use " ",same problem I encounter when I am using other methods like split, strip etc.
Try
len(!Name!.split(" "))
If that doesn't work...let us know which feature it fails on and maybe more sample data?
Try encoding the string, arc does funny things with their string encoding...
!NAME!.encode('ascii', 'ignore').count(' ') + 1
Python can not easily handle mixed double and single quotes, so it's best if you first remove them.
One way to do this is to add another field (say newName, calculate it to have the same values as "Name" field, by doing just !NAME!. I am assuming you don't want to alter the Name field.
Then within editing mode, use find and replace to replace all quotes " or ' in that new column with nothing (just don't type anything in the replace and run replace all).
Now if you use that same approach you used with this new column/field, the problem won't occur.
!newName!.count(' ') + 1

Categories

Resources