Python-基础数据类型str 字符串
前⾔
字符串是编程中最重要的数据类型,也是最常见的
字符串的表⽰⽅式单引号
双引号
多引号  、
为什么需要单引号,⼜需要双引号
因为可以在单引号中包含双引号,或者在双引号中包含单引号
多⾏字符串
正常情况下,单引号和双引号的字符串是不⽀持直接在符号间换⾏输⼊的,如果有需要可以⽤多引号哦!
转义符
在字符前加 \ 就⾏
常见的有
\n :换⾏
' '" """" """"''' '''print ("hello world")
print ('hello world')
print ("""hello world""")
# 输出结果
hello world
hello world
hello world
# 单双引号
print ("hello 'poloyy' world")
print ('this is my name "poloyy"')
# 输出结果
hello 'poloyy' world
this is  my name "poloyy"
# 多⾏字符串
print ("""
hello
world
""")
print ("""
this
is
my
name
poloyy
""")
# 输出结果
hello
world
this
is
my
name
poloyy
\t :缩进
\r :回车
栗⼦
⽐如在字符串双引号间还有⼀个双引号,就需要⽤转义符
假设 \ 只想当普通字符处理呢?
window 路径的栗⼦
更简洁的解决⽅法⽤转义符会导致可读性、维护性变差,Python 提供了⼀个更好的解决⽅法:在字符串前加
字符串运算:+ 运算
直接拼接的作⽤
字符串运算:下标和切⽚
获取字符串中某个字符
# 转义符
print ("hello \"poloyy\" world")
print ('my name is \'poloyy\'')
# 输出结果
hello "poloyy" world
my name is  'poloyy'
print ("反斜杠 \\ 是什么")
print ("换⾏符是什么 \\n")
# 输出结果
反斜杠 \ 是什么
换⾏符是什么 \n
print ("c:\nothing\rtype")
print ("c:\\nothing\\rtype")
# 输出结果
c:\nothing\
c:
type
c:\nothing\rtype
r print (r "c:\nothing\rtype")
# 输出结果
c:\nothing\rtype
# + 运算
print ("123" + "123")
print ("123" + "abc")
print ("123", "456")
# 输出结果
123123
123abc
123 456
字符串是⼀个序列,所以可以通过下标来获取某个字符
# 获取字符串某个字符
str = "hello world"
print(str[0])
print(str[1])
print(str[6])
print(str[-1])
print(str[-5])
# 输出结果
h
e
w
d
l
如果是负数,那么是倒数,⽐如 -1 就是倒数第⼀个元素,-5 就是倒数第五个元素
获取字符串中⼀段字符
Python 中,可以直接通过切⽚的⽅式取⼀段字符
切⽚的语法格式
str[start : end : step]
获取列表列表中在 [start, end) 范围的⼦字符串
start:闭区间,包含该下标的字符,第⼀个字符是 0
end:开区间,不包含该下标的字符
step:步长,设为 n,则每隔 n 个元素获取⼀次
栗⼦
print("hello world'[:] ", 'hello world'[:])  # 取全部字符
print("hello world'[0:] ", 'hello world'[0:])  # 取全部字符
print("hello world'[6:] ", 'hello world'[6:])  # 取第 7 个字符到最后⼀个字符
print("hello world'[-5:] ", 'hello world'[-5:])  # 取倒数第 5 个字符到最后⼀个字符
print("hello world'[0:5] ", 'hello world'[0:5])  # 取第 1 个字符到第 5 个字符字符串函数str
print("hello world'[0:-5] ", 'hello world'[0:-5])  # 取第 1 个字符直到倒数第 6 个字符
print("hello world'[6:10] ", 'hello world'[6:10])  # 取第 7 个字符到第 10 个字符
print("hello world'[6:-1] ", 'hello world'[6:-1])  # 取第 7 个字符到倒数第 2 个字符
print("hello world'[-5:-1] ", 'hello world'[-5:-1])  # 取倒数第 5 个字符到倒数第 2 个字符
print("hello world'[::-1] ", 'hello world'[::-1])  # 倒序取所有字符
print("hello world'[::2] ", 'hello world'[::2])  # 步长=2,每两个字符取⼀次
print("hello world'[1:7:2] ", 'hello world'[1:7:2])  # 步长=2,取第 2 个字符到第 7 个字符,每两个字符取⼀次# 输出结果
hello world'[:] hello world
hello world'[0:] hello world
hello world'[6:] world
hello world'[-5:] world
hello world'[0:5] hello
hello world'[0:-5] hello
hello world'[6:10] worl
hello world'[6:-1] worl
hello world'[-5:-1] worl
hello world'[::-1] dlrow olleh
hello world'[::2] hlowrd
hello world'[1:7:2] el
获取字符串长度
print(len("123"))
# 输出结果
3
字符串的函数
Python 提供了很多内置的字符串函数,具体可看

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。