I have a python list of strings with 000_S_0000 formatting. Since I want this list to be displayed in a LaTeX document, I want to save it first in a .txt file using a different formatting for each of its strings, specifically this one: 000\_S\_0000.
However, when I wrote the modified list in the .txt file, each string was formated as 000\\_S\\_0000 instead.
How could I solve that? Why isn't it working?
Thanks in advance!
This is my code:
def posa_barres_latex(ll_PTIDs):
for i in range(len(ll_PTIDs)):
snou = ''
for caracter in ll_PTIDs[i]:
if caracter == "_":
snou = snou + "\_"
else:
snou = snou + caracter
ll_PTIDs[i] = snou
with open("sortida_exclosos_criteri_c.txt","w") as f:
f.write(str(ll_PTIDs))
posa_barres_latex(['002_S_2043', '018_S_2138', '013_S_2324', '129_S_4073', '002_S_4237', '019_S_4285', '130_S_4468', '136_S_4517', '013_S_4791', '031_S_4194','002_S_4219', '002_S_4251', '136_S_4408', '130_S_4605', '130_S_4925', '013_S_4985'])
P.S. I am using python 3.
To print a single '\' using the print command just use:
print('\\')
The first '\' escapes the second one.
Your Python version matters in this case.
But '\' is the escape character, it's used to encode other characters, for example '\n' is a newline.
You can escape '\' as \\ and it'll just print '\'.
If you're using strings with a lot of them, it might be easier to use raw strings - just put an r in front of them. Example:
print(r"000\_S\_000")
Will print it exactly as you type it.
Related
I have a letter in LaTeX format. I'd like to write a short script in python that takes one argument (the addressee) and creates a .tex file with the general letter format and the addressee.
from sys import argv
script, addressee = argv
file = open('newletter.tex', 'w')
file.write("\begin{Document} Dear " + addressee + ", \n Greetings, how are you? Sincerely, Me \end{Document}")
file.close()
Is there a better function to write out large blocks of text? Also, you can see that the .tex file will contain programming syntax - will python disregard this as long as it is coerced to a string? Do I need to coerce a large block to string? Thanks in advance!
If you directly enter print "\begin..." into your interpreter, you will notice the result will omit the \b on the front of the string. This is because \b is a character that the print statement (or function if you're in 3.x) recognizes (it happens to be a backspace).
To avoid this confusion, you can use a "raw string", which in python is denoted by pre-pending an 'r':
>>> a = "\begin"
>>> b = r"\begin"
>>> print a
egin
>>> print b
\begin
>>>
Typically, when working with strings to represent file paths, or anything else which may contain a \ character, you should use a raw string.
As far as inserting information into a template, I would recommend using the format() function rather than string concatenation. To do this, your string would look like this:
r"\begin{{Document}} Dear {} \n Greetings, how are you? Sincerely, Me \end{{Document}}".format(addressee)
The argument of the function (in this case addressee) will be inserted into each {} within the string. For this reason, curly brackets which should be interpreted literally must be escaped by included them in duplicate.
I'd take the approach of creating the tex files first as letter.tex with the addressee set to something like QXQ_ADDRESSEE_QXQ.
The in the python script I'd read the entire file into memory. When you read from a file, it gets treated as a raw string with proper escaping.
with open('letter.tex', 'r') as f:
raw_letter = f.readlines()
Then just do a substitution and write the string to a file.
raw_letter.replace("QXQ_ADDRESSEE_QXQ", newname)
with open('newletter.tex', 'w') as f:
f.write(raw_letter)
The content of string is like this, and it has many " and many ', below is just a simple example, is there a way I can represent such a string as a constant string and assign to a variable without escape " and '. Just want to save some typing for escape " and ' and make string more readable in code. :)
--pretty-print "http://foo.com" {'bbb'}
BTW: using Python 2.7.
thanks in advance,
Lin
Use triple quotes, either single or double. You can have multiple lines in triply-quoted strings, but you don't have to.
option = """--pretty-print "http://foo.com" {'bbb'}"""
In python while reading a .txt file, if we need to remove any character at the end of a line(EOL) including escape sequences like (\n, \t,etc,.) we use rstrip('\n') like this.
But, What is the opposite of the rstrip(). I want to add a \n or \t at the end of each line in a file.
Just append the extra character:
line + "\n"
There is no real 'opposite' to str.rstrip(); that method removes an arbitrary number of characters, while you rarely would want to add a random number of new characters.
You can use + operator :
line = line+ '\n'
As mentioned you can use +
Other options are
line = '{}\n'.format(line)
line = '%s\n'%(line)
line += '\n'
Another far pulling way would be
def opposite_of_rstrip(s):
return s + '\n'
You can now use it as
line = opposite_of_rstrip(line)
EDIT
format - This is used to do various string formatting operations.
I have a text file with numbers and symbols, i want to delete some character of them and to put new line.
for example the text file is like that:
00004430474314-3","100004430474314-3","1779803519-3","100003004929477-3","100006224433874-3","1512754498-3","100003323786067
i want the output to be like that:
00004430474314
100004430474314
100003004929477
1779803519
100006224433874
1512754498
100003323786067
i tred to replace -3"," with \n by this code but it does not work. any help?
import re
import collections
s = re.findall('\w+', open('text.txt').read().lower())
print(s.replace("-3","",">\n"))
The re.findall is useless here.
with open('path/to/file') as infile:
contents = infile.read()
contents = contents.replace('-3","', '\n')
print(contents)
Another problem with your code is that you seem to think that "-3","" is a string containing -3",". This is not the case. Python sees a second " and interprets that as the end of the string. You have a comma right afterward, which makes python consider the second bit as the second parameter to s.replace().
What you really want to do is to tell python that those double quotes are part of the string. You can do this by manually escaping them as follows:
some_string_with_double_quotes = "this is a \"double quote\" within a string"
You can also accomplish the same thing by defining the string with single quotes:
some_string_with_double_quotes = 'this is a "double quote" within a string'
Both types of quotes are equivalent in python and can be used to define strings. This may be weird to you if you come from a language like C++, where single quotes are used for characters, and double quotes are used for strings.
First I think that the s object is not a string but a list and if you try to make is a string (s=''.join(s) for example) you are going to end with something like this:
0000443047431431000044304743143177980351931000030049294773100006224433874315127544983100003323786067
Where replace() is useless.
I would change your code to the following (tested in python 3.2)
lines = [line.strip() for line in open('text.txt')]
line=''.join(lines)
cl=line.replace("-3\",\"","\n")
print(cl)
Is there a way to declare a string variable in Python such that everything inside of it is automatically escaped, or has its literal character value?
I'm not asking how to escape the quotes with slashes, that's obvious. What I'm asking for is a general purpose way for making everything in a string literal so that I don't have to manually go through and escape everything for very large strings.
Raw string literals:
>>> r'abc\dev\t'
'abc\\dev\\t'
If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:
a = r"""This is a multiline string
with more than one line
in the source code."""
There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.
Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.
That is, there's no way to have the string
' ''' """ " \
properly stored in any Python string literal without internal escaping of some sort.
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
(Assuming you are not required to input the string from directly within Python code)
to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;
input_ = '/directory_of_text_file/your_text_file.txt'
input_open = open(input_,'r+')
input_string = input_open.read()
print input_string
This will print the literal text of whatever is in the text file, even if it is;
' ''' """ “ \
Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.
Use print and repr:
>>> s = '\tgherkin\n'
>>> s
'\tgherkin\n'
>>> print(s)
gherkin
>>> repr(s)
"'\\tgherkin\\n'"
# print(repr(..)) gets literal
>>> print(repr(s))
'\tgherkin\n'
>>> repr('\tgherkin\n')
"'\\tgherkin\\n'"
>>> print('\tgherkin\n')
gherkin
>>> print(repr('\tgherkin\n'))
'\tgherkin\n'