String length problems in Python

length

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容