This image comes from Google Image
Today, I find something interesting when I process some strings in my programming. The length would be different if there exists escape characters in the string. For example in the string str shown below:
str = "This is an example!"
Its length is 19.
In [1]: str = "This is an example!"
In [2]: print len(str)
19
Obviously, it is easy to check:
|len|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|str|T|h|i|s| |i|s| |a|n| |e|x|m|a|p|l|e|!|
What about this one:
string = "c:\user\image\10000.png"
We use the same way to check:
|len|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|str|c|:||u|s|e|r||i|m|a|g|e||1|0|0|0|0|.|p|n|g|
Then we double check in the code:
In [1]: string = "c:\user\image\10000.png"
In [2]: print len(string)
20
It turns out that we are wrong when there are escape characters
. In the string, there are three
escape characters. So its length should be 23-3=20
because escape characters do not count unless there is a double escape character like "\\\\"
. Plus, it will count one in strings.
For instance:
str1 = "c:\\user\\10000.png"
Its length is 17.
|len|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|str|c|:|\\|u|s|e|r|\\|1|0|0|0|0|.|p|n|g|
In [5]: str1 = "c:\\user\\10000.png"
In [6]: print len(str1)
17
Based on above content, you may have a deep understanding of strings when you are using rfind
. If I want to extract the name of png image in str1
, I need to find out the position of \\\\
and use the cutting operations in Python.
In [9]: str1 = "c:\\user\\10000.png"
In [10]: pos = str1.rfind("\\")
In [11]: print str1[pos+1:]
10000.png
Please guarantee that you use "\\\\"
instead of "\\"
in your code, otherwise you will not get the name of the png image.
In [4]: str1 = "c:\user\10000.png"
In [5]: print str1[str1.rfind("\\")+1:]
user@00.png
This is because "\100"
is @
here.
In [6]: print "\100"
@
Last but not least:
The rfind() method returns the highest index of the substring (if found). If not found, it returns -1.
In [8]: str1 = "c:\\user\\10000.png"
In [9]: str1.rfind("@")
Out[9]: -1