How do I add the ' symbol to a string - python-3.x

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.)

Related

How to remove forward slash (\) from a string in Python?

I am trying to remove all the backslashes from a string in my code, however when I tried the following:
a = 'dfdfd\dafdfd'
print(a)
a.replace('\',' ')
... I encountered the following error:
File "<stdin>", line 1
a.replace('\',' ')
Can someone explain why this is happening, and how do I fix it?
You need to use raw r'' string -
a.replace(r'\',' ')
You can this way(One more way to do):
a = 'dfdfd\dafdfd'
exclude = '\\'
s = ''.join(ch for ch in a if ch not in exclude)
print(s)
The backslash (\) character is an escape character. When you wrote
a.replace('\',' ')
... Python interpreted the \' as a ' inside the string, and therefore threw an error since the parser messed up. Therefore, you need to fix this by escaping the backslash character with another backslash, like so:
a.replace('\\',' ')

Replace two backslashes with a single backslash

I want to replace a string with two backslashes with single backslashes. However replace doesn't seem to accept '\\' as the replacement string. Here's the interpreter output:
>>> import tempfile
>>> temp_folder = tempfile.gettempdir()
>>> temp_folder
'C:\\Users\\User\\AppData\\Local\\Temp'
>>> temp_folder.replace('\\\\', '\\')
'C:\\Users\\User\\AppData\\Local\\Temp'
BTW, I know that Windows paths need to contain either double backslashes or a single forward slashes. I want to replace them anyway for display purposes.
Your output doesn't have double backslashes. What you are looking at is the repr() value of the string and that displays with escaped backslashes. Assuming your temp_folder would have double backslashes, you should instead use:
print(temp_folder.replace('\\\\', '\\'))
and that will show you:
C:\Users\User\AppData\Local\Temp
which also drops the quotes.
But your temp_folder is unlikely to have double backslashes and this difference in display probably got you thinking that there are double backslashes in the return value from tempfile.gettempdir(). As #Jean-Francois indicated, there should not be (at least not on Windows). So you don't need to use the .replace(), just print:
print(temp_folder)
This works for me
text = input('insert text')
list = text.split('\\')
print(list)
text2 = ''
for items in list:
if items != '':
text += items + '\\'
print(text2)

' vs " " vs ' ' ' in Groovy .When to Use What?

I am getting really confused in Groovy. When to use what for Strings in Groovy ?
1) Single Quotes - ' '
2) Double Quotes - " "
3) Triple Quotes - '''
My code:
println("Tilak Rox")
println('Tilak Rox')
println('''Tilak Rox''')
All tend to produce same results.
When to Use What ?
I would confuse you even more, saying, that you can also use slash /, dolar-slash $/ and triple-double quotes """ with same result. =)
So, what's the difference:
Single vs Double quote: Most important difference. Single-quoted is ordinary Java-like string. Double-quoted is a GString, and it allows string-interpolation. I.e. you can have expressions embedded in it: println("${40 + 5}") prints 45, while println('${ 40 + 5}') will produce ${ 40 + 5}. This expression can be pretty complex, can reference variables or call methods.
Triple quote and triple double-quote is the way to make string multiline. You can open it on one line in your code, copy-paste big piece of xml, poem or sql expression in it and don't bother yourself with string concatenation.
Slashy / and dollar-slashy $/ strings are here to help with regular expressions. They have special escape rules for '\' and '/' respectfully.
As #tim pointed, there is a good official documentation for that, explaining small differences in escaping rules and containing examples as well.
Most probably you don't need to use multiline/slashy strings very often, as you use them in a very particular scenarios. But when you do they make a huge difference in readability of your code!
Single quotes ' are for basic Strings
Double quotes " are for templated Strings ie:
def a = 'tim'
assert "Hi $a" == 'Hi tim'
Triple single quotes ''' are for multi-line basic Strings
Triple double """ quotes are for multi-line templated strings
There's also slashy strings /hello $a/ which are templated
And dollar slashy Strings $/hello $a/$ which are multi-line and templated
They're all documented quite well in the documentation

Python - exclude data with double quotes and parenthesis

I have a list which contains set of words in single quotes and double quotes, now i want to grep all the data only in single quotes.
Input_
sentence = ['(telco_name_list.event_date','reference.date)',"'testwebsite.com'",'data_flow.code',"'/long/page/data.jsp'"]
Output:
telco_name_list.event_date,reference.date,data_flow.code
I want to exclude the parenthesis and string in double quotes.
Since you tagged the post as python-3.x, I'm assuming you want to write python code. Based on your example this would work:
#!/usr/bin/env python3
Input_sentence = ['(telco_name_list.event_date','reference.date)',"'testwebsite.com'",'data_flow.code',"'/long/page/data.jsp'"]
comma = False
result = []
for i in range(len(Input_sentence)):
e = Input_sentence[i]
if e.startswith("'"): continue
e = e.replace('(', '').replace(')', '')
if comma:
print(",", end="")
comma = True
print(e, end="")
print()
This code iterates through the list, ignoring elements which begin with a single quote and filtering out parentheses from elements before printing them on stdout. This code works for the given example, but may or may not be what you need as the exact semantics of what you want out are somewhat ambiguous (i.e. is it fine to filter out all parentheses or just the ones at the beginning and end of your elements?).

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,'_','\_'))

Resources