实例(Python 3.0+)
#!/usr/bin/python3str='123456789'print(str) # 输出字符串print(str[0:-1]) # 输出第一个到倒数第二个的所有字符print(str[0]) # 输出字符串第一个字符print(str[2:5]) # 输出从第三个开始到第五个的字符print(str[2:]) # 输出从第三个开始后的所有字符print(str[1:5:2]) # 输出从第二个开始到第五个且每隔一个的字符(步长为2)print(str * 2) # 输出字符串两次print(str + '你好') # 连接字符串print('------------------------------')print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
这里的 r 指 raw,即 raw string,会自动将反斜杠转义,例如:
>>>print('\n') # 输出空行
>>>print(r'\n') # 输出 \n
\n
>>>
以上实例输出结果:
123456789
12345678
1
345
3456789
24
123456789123456789
123456789你好
------------------------------
hello
runoob
hello\nrunoob