Use single quote and double quote same time as string python - python

How can I use single quote and double quote same time as string python?
For example:
string = "Let's print "Happines" out"
result should be Let's print "Happines" out
I tried to use backslash but it prints out a \ before 's that should be.

In python there's lots of ways to write string literals.
For this example you can:
print('Let\'s print "Happiness" out')
print("Let's print \"Happiness\" out")
print('''Let's print "Happiness" out''')
print("""Let's print "Happiness" out""")
Any of the above will behave as expected.

Taking this string:
string = "Let's print "Happines" out"
If you want to mix quotes, use the triple single quotes:
>>> string = '''Let's print "Happines" out'''
>>> print(string)
Let's print "Happines" out
Using triple quotes is acceptable too:
>>> string = """Let's print "Happines" out"""
>>> print(string)
Let's print "Happines" out

Related

Non-ASCII characters appearing in string

So I need to compare 2 strings :
str1 = 'this is my string/ndone'
str2 = 'this is my string done'
So I replace the new line from str1 with ' ':
new_str = str1.replace('\n', ' ')
And when print the 2 strings there are identical:
'this is my string done'
But when compared using == operator the not so I convert this 2 strings into array to see why they are not equal:
arr1 = bytearray(str1 , 'utf-8')
print(arr1)
arr2 = bytearray(str2 , 'utf-8')
print(arr2)
And this is the output:
str1 = bytearray(b'this is\xc2\xa0my string done')
str2 = bytearray(b'this is my string done')
So what is this \xc2\xa0 ?
'\xc2\xa0' is the UTF-8 encoding of the Unicode character 'NO-BREAK SPACE' (U+00A0).
use python unidecode library
from unidecode import unidecode
str = "this is\xc2\xa0my string done"
print(unidecode(str))
o/p
this isA my string done
== is working in comparing two string
str1 = 'this is my string\ndone'
str2 = 'this is my string done'
str1 = str1.replace("\n"," ")
print(str1)
if (str1 == str2):
print("y")
else:
print("n")
and output is
this is my string done
y
As stated elsewhere your string had a "/n" not "\n" in it.
Assuming though that what you wanted to do was normalise all whitespace characters, this is a very handy trick I use all the time:
string = ' '.join(string.split())
Update: Okay this is why:
If you don't specify what string.split() should use a separater the, per docs:
If sep is not specified or is None, a different splitting algorithm is
applied: runs of consecutive whitespace are regarded as a single
separator, and the result will contain no empty strings at the start
or end if the string has leading or trailing whitespace.
So it splits on whitspaces, and treats multiple whitespaces as a single seperator. I don't know what characters are all defined as "whitespaces", but is certainly includes all the usual suspects. Then when you rejoin the list into a string with ' '.join(), you know for sure that all whitespaces are now the same.

How to replace single quotes within a string with quoted double quotes

For example:
Input:
{'match_all':{}}
Output:
{'"match_all"':{}}
Is there some regex that can do this?
I know I could iterate through the string and whenever I encounter a key replace each side of it with ‘“ followed by “‘; however, I was wondering if any of you knew a more pythonic way of doing this.
why not try using this method: https://www.tutorialspoint.com/python/string_replace.htm and try to replace, ' for '" and the second ' for "'...
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
the output returns:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
print str.replace("'", "'"")
print str.replace("'", ""'", 1)
use ' " as needed to avoid errors...

Why does Python return an escaping backslash in a string?

'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
gives as output:
'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
Why is the escape character showing up in the output?
When I type the string below, this doesn't happen.
'This is a codon, isn\'t it?'
The output I get is this:
"This is a codon, isn't it?"
because in first one the whole string is in one-quote so another one-quotes should be escaped. Whereas in second one the whole string is in double quote.
>>> '\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered'
'"atg is a codon, isn\'t it?" "Yes, it is", he answered'
^ ^
>>>
>>> 'This is a codon, isn\'t it?'
"This is a codon, isn't it?" # there is no need to escape the one-quote between double-quotes
^ ^
The escape character is needed because that is the string that, if typed out exactly, would reproduce the string. The string contains both single and double quotes, so whichever type encloses the string will need to be escaped within the string.
You get to choose either single quotes or double quotes to enclose a string. Any occurrences of your enclosing quote character must be escaped with a '\'.
>>> b = 'Hello\'s'
>>> a = "Hello's"
>>> b = 'Hello\'s'
>>> c = 'Hello"s'
>>> d = "Hello\"s"
>>> a
"Hello's"
>>> b
"Hello's"
>>> c
'Hello"s'
>>> d
'Hello"s'
>>>

How do I use a escape sequence with a variable?

a = "test"
b = "testing"
print a\nb
Is there a way I can use an escape sequence with a variable, or is it unnecessary?
If you are trying to print string variables by separating them with the newline character ('\n'), you can do so like this:
a = "Hello"
b = "World"
print(a+"\n"+b)
See demo here
Simply executing two separate print statements would also give a similar effect, this is because each print statement automatically inserts a newline character.
a = "Hello"
b = "World"
print(a)
print(b)
So it isn't necessary to use the newline character to escape a string while printing.
In case you'll have more to print/format in the future a maintainable solution would be,
l = [ 'Hello', 'world' ]
# Print with newlines
print('\n'.join(l))
# Print with tabs
print('\t'.join(l))
See https://docs.python.org/2/library/string.html?highlight=string%20join#string.join.

Regex sub function not working with unicode string

I'm trying to use Python's sub function and I'm having a problem getting it to work. From the troubleshooting I've been doing I believe it has something to do with the unicode characters in the string.
# -*- coding: utf-8 -*-
reload(sys)
sys.setdefaultencoding('utf-8')
import re
someFunction(string):
string = string.decode('utf-8')
match = re.search(ur'éé', string)
if match:
print >> sys.stderr, "It was found"
else:
print >> sys.stderr, "It was NOT found"
if isinstance(string, str):
print >> sys.stderr, 'string is a string object'
elif isinstance(string, unicode):
print >> sys.stderr, 'string is a unicode object'
new_string = re.sub(ur'éé', ur'é:', string)
return new_string
stringNew = 'éégktha'
returnedString = someFunction(stringNew)
print >> sys.stderr, "After printing it: " + returnedString
#At this point in the code string = 'éégktha'
returnString = someFunction(string)
print >> sys.stderr, "After printing it: " + returnedString
So I would like 'é:gktha'. Below is what is printed to the error log when I run this code.
It was found
string is a unicode object
é:gktha
It was NOT found
string is a unicode object
éégktha
So I'm thinking it must be something with string that is passed into my function. When I declared is as a unicode string or a string literal and then decode it the pattern is found. But the pattern is not being found in the string being passed in. I was thinking my string = string.decode('utf-8') statement would convert any string passed into the function and then would would work.
I tried to do this in the python interpreter to work through this and when I declare string as a unicode string it works.
string = u'éégktha'
So to simulate the function I declared the string and then 'decode' it to and then tried my regex statement and it worked.
string = 'éégktha'
newString = string.decode('utf8')
string = re.sub(ur'éé', ur'é:', newString)
print string #é:gktha
This web app that works with a lot of unicode characters. This is Python 2.5 and I've always had a hard time when working with unicode characters. Any help and knowledge is greatly appreciated.
You should print what it returned by someFunction.
>>> string = 'éégktha'
>>> def someFunction(string):
... #string = 'éégktha'
... string = string.decode('utf8')
... new_string = re.sub(ur'éé', ur'é:', string)
... return new_string
>>> import re
>>> someFunction(string)
u'\xe9:gktha'
>>> print someFunction(string)
é:gktha
Your functions fine. In the simulation you are printing which prints what is returned by __str__ while when you return the interpreter prints what is returned by the __repr__ of the new_string/newString.

Categories