\n in Python 3 confusion - python-3.x

I am pretty new at python. So, I get this
SyntaxError: unexpected character after line continuation character
after running this:
print (full_name.title()\nfull_name.upper()\nfull_name.lower())
Any idea why?

You must separate each string by a comma, and the use quotes around the strings:
print(full_name.title(), '\n', full_name.upper(), '\n', full_name.lower())
Alternatively, you could first concatenate the fragments, then print the resulting string:
string_to_print = full_name.title() + '\n' + full_name.upper() + '\n' + full_name.lower()
print(string_to_print)
There are more sophisticated approaches too (f-strings, format, __str__, etc.) that you may want to look up once you have mastered the basics.

Related

How do I add the ' symbol to a string

I had someone help with a prior question to turn hexadecimal to string, but I want the string to output surrounded with '
so it returns 'I0KB' instead of just I0KB.
What I have:
with open('D:\new 4.txt', 'w') as f:
f.write('if not (GetItemTypeId(GetSoldItem())==$49304B42) then\n')
def hex_match_to_string(m):
return ''.join([chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)])
# ...
line = re.sub(r'\$((?:\w\w\w\w\w\w\w\w)+)', hex_match_to_string, line)
file_out.write(line)
output:
if not (GetItemTypeId(GetSoldItem())==I0KB) then
but I want it to output
if not (GetItemTypeId(GetSoldItem())=='I0KB') then
and using
def hex_match_to_string(m):
return ''.join(',[chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)],')
...gives me a syntax error even though I read that join(a,b,c) is the way to combine strings.
Thanks in advance for the help, and sorry I am clueless for what should be an easy task.
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.
You should not add the quotes to the argument passed to join, but wrap the result of the join with quotes:
return "'" + ''.join([chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)]) + "'"
I think it's important to distinguish between enclosing a string between, single, double, or triple quotation marks. See answers here regarding the most common use of the third (the so-called doc-strings).
While most of the time you can use " and ' interchangeably, you can use them together in order to escape the quotation:
>>> print("''")
''
>>> print('"')
"
You can also use the double quotes three times to escape any double quotes in between:
>>> print(""" " " "j""")
" " "j
But I'd suggest against the last option, because it doesn't always work as expected, for example, print(""""""") will throw an error. (And of course, you could always use the \ to escape any special character.)

Multiple checks but still SyntaxError: EOL while scanning string literal

I have checked on this string multiple times to ensure that the (".") are in place, but the message
File "<ipython-input-13-ef09f7b4583b>", line 48 plt.savefig("C:\scratch\\data\"+str(angle).zfill(3)+".")
SyntaxError: EOL while scanning string literal
still comes up.
Any suggestions?
if save is not False:
plt.savefig("C:\scratch\\data\"+str(angle).zfill(3)+".png")
plt.close("all")
else:
plt.show()
return
A Python string can not terminate with \ as this will escape the closing " (or ').
You have several options:
Use double-back slashes in a constant manner:
plt.savefig("C:\\scratch\\data\\" + str(angle).zfill(3) + ".png")
Use .format, preferably with combination of raw string to avoid problems in case a directory name starts with t, n or any other character that will become a control sequence when prefixed with \:
plt.savefig(r"C:\scratch\data\{}.png".format(str(angle).zfill(3)))

How to put a line break in HDF5 attribute string in Matlab

I would like to know how to put a line break in below HDF5 attribute string.
DescType_id = H5T.copy ('H5T_C_S1');
H5T.set_size (DescType_id, numel(description));
H5T.set_strpad(DescType_id,'H5T_STR_NULLTERM');
DescAttr_id = H5A.create (g2id, 'description', DescType_id, ...
STimeSpace, 'H5P_DEFAULT');
H5A.write (DescAttr_id, DescType_id, description);
H5T.close(DescType_id);
H5A.close(DescAttr_id);
My description variable would be:
description="Experiment:\nID: 1234\nLocation: London"
I am expecting the line break character to be something like '\n' in above code. Expected Output:
Group '/'
Group '/G1'
Attributes:
'description': 'Experiment:
ID: 1234
Location: London'
Your help is greatly appreciated. Thanks.
You should set description to the correct string:
description = sprintf('Experiment:\nID: 1234\nLocation: London');
One should note that the usual escape sequences are actually interpreted by the I/O functions (i.e. fprintf, sprintf) and not by the MATLAB language parser. That means, for example, that the literal '\n' (in MATLAB) is a char array of two chars, a backslash and an n, while in C the literal "\n" is a const char array of two chars, one being a new-line, and the other being the string terminator NUL.
A non-portable but "equivalent" way of writing the above description would be concatenating the sub-strings with the line separators:
description = ['Experiment:' char(10) 'ID: 1234' char(10) 'Location: London'];
where char(10) is the char that has the UTF-8 code 10, which happens to be the new-line character.

Convert underscores to spaces in Matlab string?

So say I have a string with some underscores like hi_there.
Is there a way to auto-convert that string into "hi there"?
(the original string, by the way, is a variable name that I'm converting into a plot title).
Surprising that no-one has yet mentioned strrep:
>> strrep('string_with_underscores', '_', ' ')
ans =
string with underscores
which should be the official way to do a simple string replacements. For such a simple case, regexprep is overkill: yes, they are Swiss-knifes that can do everything possible, but they come with a long manual. String indexing shown by AndreasH only works for replacing single characters, it cannot do this:
>> s = 'string*-*with*-*funny*-*separators';
>> strrep(s, '*-*', ' ')
ans =
string with funny separators
>> s(s=='*-*') = ' '
Error using ==
Matrix dimensions must agree.
As a bonus, it also works for cell-arrays with strings:
>> strrep({'This_is_a','cell_array_with','strings_with','underscores'},'_',' ')
ans =
'This is a' 'cell array with' 'strings with' 'underscores'
Try this Matlab code for a string variable 's'
s(s=='_') = ' ';
If you ever have to do anything more complicated, say doing a replacement of multiple variable length strings,
s(s == '_') = ' ' will be a huge pain. If your replacement needs ever get more complicated consider using regexprep:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
That being said, in your case #AndreasH.'s solution is the most appropriate and regexprep is overkill.
A more interesting question is why you are passing variables around as strings?
regexprep() may be what you're looking for and is a handy function in general.
regexprep('hi_there','_',' ')
Will take the first argument string, and replace instances of the second argument with the third. In this case it replaces all underscores with a space.
In Matlab strings are vectors, so performing simple string manipulations can be achieved using standard operators e.g. replacing _ with whitespace.
text = 'variable_name';
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
=> text = variable name
I know this was already answered, however, in my case I was looking for a way to correct plot titles so that I could include a filename (which could have underscores). So, I wanted to print them with the underscores NOT displaying with as subscripts. So, using this great info above, and rather than a space, I escaped the subscript in the substitution.
For example:
% Have the user select a file:
[infile inpath]=uigetfile('*.txt','Get some text file');
figure
% this is a problem for filenames with underscores
title(infile)
% this correctly displays filenames with underscores
title(strrep(infile,'_','\_'))

Syntax error in removing bad character in groovy

Hello I have a string like a= " $ 2 187.00" . I tried removing all the white spaces and the bad characters like a.replaceAll("\\s","").replace("$","") . but i am getting error
Impossible to parse JSON response: SyntaxError: JSON.parse: bad escaped character how to remove the bad character in this expression so that the value becomes 2187.00.Kindly help me .Thanks in advance
def a = ' $ 2 187.00'
a.replaceAll(/\s/,"").replaceAll(/\$/,"")
// or simply
a.replaceAll(/[\s\$]/,"")
It should return 2187.00.
Note
that $ has special meaning in double quoted strings literals "" , called as GString.
In groovy, you can user regex literal, using that is better than using regex with multiple escape sequences in string.

Resources