1.字符串 Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。如下图:

实例:
# -*- coding: utf-8 -*-
# @Time : 2022/3/23 17:44
# @File : string.py
# @Software : PyCharm
str = 'HelloWorld'
#索引值以 0 为开始值,-1 为从末尾的开始位置。
print (str) # 输出字符串
print (str[0:-1]) # 输出第一个到倒数第二个的所有字符
print (str[0]) # 输出字符串第一个字符
print (str[2:5]) # 输出从第三个开始到第五个的字符
print (str[2:]) # 输出从第三个开始的后的所有字符
print (str * 2) # 输出字符串两次,也可以写成 print (2 * str)
print (str + "Welcome to Python world!") # 连接字符串
#Python 使用反斜杠 \ 转义特殊字符,如果你不想让反斜杠发生转义,可以在字符串前面添加一个 r,表示原始字符串
print('Hello\nWorld')
print(r'Hello\nWorld')
#注意,Python 没有单独的字符类型,一个字符就是长度为1的字符串。
word = 'Python'
#与 C 字符串不同的是,Python 字符串不能被改变。
print(word[0], word[5])
word[0]='p' #错误:Python 字符串不能被改变。
运行结果:
HelloWorld
HelloWorl
H
llo
lloWorld
HelloWorldHelloWorld
HelloWorldWelcome to Python world!
Hello
World
Hello\nWorld
P n
Traceback (most recent call last):
File "G:\python_lesson\helloworld\string.py", line 26, in <module>
word[0]='p' #错误:Python 字符串不能被改变。
TypeError: 'str' object does not support item assignment