python系列均基於python3.4環境
1、自然字符串和重復字符串
- 代碼示例:
str1=r'hello \npython' str2='hello \npython' str3="hello python\n"*3 print("str1: {0}".format(str1)) print("str2: {0}".format(str2)) print("str3: {0}".format(str3))
- 運行結果:
- 結果分析:
(1)str1為自然字符串,輸出結果保留原來的格式,不受轉義影響
(2)str2為非自然字符串,輸出結果受轉義影響
(3)str3為原字符串重復3次
2、子字符串
(1)索引從0開始
(2)切片運算符[x:y]表示:x<=(下標)<y
- 代碼示例:
str="hello,python" substring1=str[0] #索引為0的字符 substring2=str[6] #索引為6的字符 substring3=str[:5] #截取索引從0到(5-1)的字符 substring4=str[6:] #截取索引從6到結束的字符 substring5=str[6:8] #截取索引從6到(8-1)的字符 print("substring1: {0}".format(substring1)) print("substring2: {0}".format(substring2)) print("substring3: {0}".format(substring3)) print("substring4: {0}".format(substring4)) print("substring5: {0}".format(substring5))
- 運行結果: