InterviewSolution
| 1. |
What is difference between string and raw string? |
||||||||||||||
|
Answer» Literal representation of Python string can be DONE using single, double or triple quotes. Following are the different ways in which a string object can be declared: >>> s1='HELLO Python' >>> s2="Hello Python" >>> s3='''Hello Python''' >>> s4="""Hello Python"""However, if a string contains any of the escape sequence characters, they are embedded inside the quotation marks. The back-slash character followed by certain alphabets carry a special meaning. Some of the escape characters are:
In case of a raw string on the other hand the escape characters don’t get translated while printing. Such raw string is prepared by prefixing ‘r’ or ‘R’ to the leading quotation mark(single, double or triple) >>> r1=r'Hello\nPython' >>> print (r1) Hello\nPython >>> r2=R"Hello\tPython" >>> print (r2) Hello\tPythonPython doesn’t allow any undefined escape sequence to be embedded in the quotation marks of a normal string. >>> s1='Hello\xPython' SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 5-6: truncated \xXX escapeHowever, in a raw string, any character followed by backslash may be used because ANYWAY it is not going to be interpreted for its meaning! >>> s1=r'Hello\xPython' >>> print (s1) Hello\xPythonRaw strings are used in building regular expressions (called regex). Python’s re module provides functions to process the regular expressions. The re module assigns its own escape characters. Some of them are listed below:
Some examples of above escape characters are given below: >>> import re >>> string='ab12cd34ef' >>> #find all digits >>> x = re.findall("\d", string) >>> print (x) ['1', '2', '3', '4'] >>> #find all non-digit characters >>> x = re.findall("\D", string) >>> print (x) ['a', 'b', 'c', 'd', 'e', 'f'] |
|||||||||||||||