I'm trying to pprint() in Sympy a variable that I call barphi. What I want to get is
$\bar{\phi}$
when printed as pprint(barphi).
I try
barphy = Symbol('\bar{phi}')
but it does not work. Any help? Thanks in advance.
This was answered on the SymPy mailing list.
There are two issues with what you wrote
First, Python converts \ + character in strings as escaping. The \b in your string becomes a backspace (see https://en.wikipedia.org/wiki/ASCII#ASCII_control_code_chart).
You need to either escape the \, i.e., use '\\bar{\\phi}$', or, much easier, if you don't care about escaping, use a raw string, which just means to put an r in front of the quotes, like r'\bar{\phi}'.
Second, if you want to get LaTeX, pprint() will not do it (pprint pretty prints to 2D text). You should use init_printing() to enable LaTeX printing in the notebook.
Finally, as pointed out by Julien Rioux on the mailing list, you can just name the symbol phibar, and SymPy will automatically render it as \bar{\phi}, as you can see here even in Unicode
In [11]: Symbol('phibar')
Out[11]: φ̅
If you still want to get the latex code rather than printing it, you can do so by:
In [2]: from sympy.printing.latex import latex, translate
In [3]: latex(translate('phibar'),mode='inline')
Out[3]: '$\\bar{\\phi}$'
you can see the documentation for latex function here
The documentation for translate function are
Check for a modifier ending the string. If present, convert the
modifier to latex and translate the rest recursively.
Given a description of a Greek letter or other special character,
return the appropriate latex.
Let everything else pass as given.
>>> from sympy.printing.latex import translate
>>> translate('alphahatdotprime')
"{\\dot{\\hat{\\alpha}}}'"
Related
I'm basically trying to make a quine in python and first tried with f-strings, but I quickly realized that I first have to define the variables I want to format inside the string. I then learned about string templates and figured that would be the way to go. I am however not that experienced with it and could need some help. Any suggestions?
Here's the actual code:
from string import Template
s="from string import Template\ns=$s\nt=Template($s).substitute(s=$s)\nprint($s)"
t=Template(s).substitute(s=s)
print(s)
It gives me somewhat of the right result. The only problem is that it's not replacing the $s with the actual string. I've might just have misunderstood the whole concept with quines and the method of doing them but I feel this should work.
Output:
from string import Template
s=$s
t=Template($s).substitute(s=$s)
print($s)
I'm not sure how this would be done using string.Template, but you could use str.format as a straightforward replacement to f-strings that suits this task, as it allows you to delay the interpolation of the s variable:
s='s={0!r}\nprint(s.format(s))'
print(s.format(s))
Output:
s='s={0!r}\nprint(s.format(s))'
print(s.format(s))
The !r is used to get the repr of s, which wraps it in quotes, and escapes the newlines.
I've taken the advice from #Will Da Silva and included the repr() function in my method of doing it as seen below:
from string import Template
s='from string import Template\ns=$s\nt=Template(s)\nprint(t.substitute(s=repr(s)))'
t=Template(s)
print(t.substitute(s=repr(s)))
I think the problem was that it interpreted the string as code and in turn made a new line at every \n. But now when it keeps the quotation marks it just sees it as a string.
In Python 3.3, is there any way to make a part of text in a string subscript when printed?
e.g. H₂ (H and then a subscript 2)
If all you care about are digits, you can use the str.maketrans() and str.translate() methods:
example_string = "A0B1C2D3E4F5G6H7I8J9"
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
print(example_string.translate(SUP))
print(example_string.translate(SUB))
Which will output:
A⁰B¹C²D³E⁴F⁵G⁶H⁷I⁸J⁹
A₀B₁C₂D₃E₄F₅G₆H₇I₈J₉
Note that this won't work in Python 2 - see Python 2 maketrans() function doesn't work with Unicode for an explanation of why that's the case, and how to work around it.
The output performed on the console is simple text. If the terminal supports unicode (most do nowadays) you can use unicode's subscripts. (e.g H₂) Namely the subscripts are in the ranges:
0x208N for numbers, +, -, =, (, ) (N goes from 0 to F)
0x209N for letters
For example:
In [6]: print(u'H\u2082O\u2082')
H₂O₂
For more complex output you must use a markup language (e.g. HTML) or a typesetting language (e.g. LaTeX).
Using code like this works too:
print('\N{GREEK SMALL LETTER PI}r\N{SUPERSCRIPT TWO}')
print('\N{GREEK CAPITAL LETTER THETA}r\N{SUBSCRIPT TWO}')
The output being:
πr²
Θ₂
Note that this works on Python versions 3.3 and higher only. Unicode formatting.
If you want to use it on the axes of a plot you can do:
import matplotlib.pyplot as plt
plt.plot([1])
plt.ylabel(r'$H_{2}$')
plt.show()
which gives
By using this code you can use alphabets on the superscript and subscript
In This code
format() is Function and in Format function ('\unicode')
By using this table (Unicode subscripts and superscripts on Wikipedia) you can give suitable unicode to the suitable one
you can use superscript and sub script
"10{}".format('\u00B2') # superscript 2
I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\', I know I can do:
print(r'C:\\Windows\Users\alexb\')
But I cant put an r in front of a variable.... for instance:
test = 'C:\\Windows\Users\alexb\'
print(rtest)
Clearly would just try to print rtest.
I also know there's
test = 'C:\\Windows\Users\alexb\'
print(repr(test))
But this returns 'C:\\Windows\\Users\x07lexb'
as does
test = 'C:\\Windows\Users\alexb\'
print(test.encode('string-escape'))
So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just
print(raw(test))
But its not
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
In general, to make a raw string out of a string variable, I use this:
string = "C:\\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
'C:\\\\Windows\\Users\\alexb'
You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.
I know i'm too late for the answer but for people reading this I found a much easier way for doing it
myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
try this. Based on what type of output you want. sometime you may not need single quote around printed string.
test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'")) # output: qweqwe\n1212as\t121\\2asas
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:
test = 'C:\\Windows\Users\alexb\'
rawtest = r'%s' %test
I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com.
But when I print it in the interactive mode I get double slash - '\\w'
as #Jimmynoarms said:
The Solution for python 3x:
print(r'%s' % your_variable_pattern_str)
Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.
Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.
You can do it two ways:
>>>print("C:\\Windows\Users\alexb\\")
C:\Windows\Users\alexb\
>>>print(r"C:\\Windows\Users\alexb\\")
C:\\Windows\Users\alexb\\
Store it in a variable:
test = "C:\\Windows\Users\alexb\\"
Use repr():
>>>print(repr(test))
'C:\\Windows\Users\alexb\\'
or string replacement with %r
print("%r" %test)
'C:\\Windows\Users\alexb\\'
The string will be reproduced with single quotes though so you would need to strip those off afterwards.
To turn a variable to raw str, just use
rf"{var}"
r is raw and f is f-str; put them together and boom it works.
Replace back-slash with forward-slash using one of the below:
re.sub(r"\", "/", x)
re.sub(r"\", "/", x)
This does the trick
>>> repr(string)[1:-1]
Here is the proof
>>> repr("\n")[1:-1] == r"\n"
True
And it can be easily extrapolated into a function if need be
>>> raw = lambda string: repr(string)[1:-1]
>>> raw("\n")
'\\n'
i wrote a small function.. but works for me
def conv(strng):
k=strng
k=k.replace('\a','\\a')
k=k.replace('\b','\\b')
k=k.replace('\f','\\f')
k=k.replace('\n','\\n')
k=k.replace('\r','\\r')
k=k.replace('\t','\\t')
k=k.replace('\v','\\v')
return k
Here is a straightforward solution.
address = 'C:\Windows\Users\local'
directory ="r'"+ address +"'"
print(directory)
"r'C:\\Windows\\Users\\local'"
I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the \frac{}{} part) yields the error:
Normalized Distance in Chamber ($
rac{x}{L}$)
^
Expected end of text (at char 32), (line:1, col:33)
The math mode seems to work fine for everything else I've tried (symbols mostly, e.g. $\mu$ works fine and displays µ) so I'm not sure what is happening here. I've looked up other peoples code for examples and they just seem to use \frac{}{} with nothing special and it works fine. I don't know what I'm doing differently. Here is the code. Thanks for the help!
import numpy as np
import math
import matplotlib.pylab as plt
[ ... bunch of calculations ... ]
plt.plot(xspace[:]/L,vals[:,60])
plt.axis([0,1,0,1])
plt.xlabel('Normalized Distance in Chamber ($\frac{x}{L}$)')
plt.savefig('test.eps')
Also, I did look up \f and it seems its an "escape character", but I don't know what that means or why it would be active within TeX mode.
In many languages, backslash-letter is a way to enter otherwise hard-to-type characters. In this case it's a "form feed". Examples:
\n — newline
\r — carriage return
\t — tab character
\b — backspace
To disable that, you either need to escape the backslash itself (backslash-backslash is a backslash)
'Normalized Distance in Chamber ($\\frac{x}{L}$)'
Or use "raw" strings where escape sequences are disabled:
r'Normalized Distance in Chamber ($\frac{x}{L}$)'
This is relevant to Python, not TeX.
Documentation on Python string literals
"\f" is a form-feed character in Python. TeX never sees the backslash because Python interprets the \f in your Python source, before the string is sent to TeX. You can either double the backslash, or make your string a raw string by using r'Normalized Distance ... etc.'.
You have to add an r front of the string to avoid parsing the \f.
I have been making an mp3 player with Tkinter and the module mp3play.
Say i had the song to play: C:\Music\song.mp3
and to play that song i have to run this script:
import mp3play
music_file=r'C:\Music\song.mp3'
clip = mp3play.load(music_file)
clip.play()
Easy enough, my problem though is getting the "r" there.
i have tried:
import mp3play
import re
music_file="'C:\Music\song.mp3'"
music_file='r'+music_file
music_file=re.sub('"','',music_file)
print music_file
clip = mp3play.load(music_file)
clip.play()
Which gets the output: r'C:\Music\song.mp3'
but it is a string, so it wont read the file.
The 'r' in the front denotes a particular category of string called raw string. You can't get that by adding two strings or re substituting a string. It is just a string type, but with the escape characters take care.
>>> s = r'something'
>>> s
'something'
>>>
When you are writing the script, use the 'r', if you are getting the input via raw_input, python will take care of escaping the characters. So, the question is why are you trying to do that?
try:
music_file='C:/Music/song.mp3'
In Python, the r prefix introduces a raw string. Outside of raw strings, backslash (\) characters are considered as escape characters and have to be escaped themselves (by doubling them).
Try a simple string instead:
music_file = 'C:\\Music\\song.mp3'
The r you are talking about has to be placed before a string definition, and tells python that the following string is "raw", meaning it will ignore backslash escapes (so it doesn't error on invalid backslashes in filenames, for example).
Why don't you just do it like in the first example? I don't see what you are trying to accomplish in the second example.
you can try music_file = r'%s' % path_to_file
As a few of the other answers have pointed out (I'm just posting this as an answer because it seemed kind of silly to make it a comment), what you've given in your first code block is exactly what the contents of your script should be. You don't need to do anything special to get the r there. In fact the 'r' is not part of the string, it's part of the code that makes the string.