Pyhon基础数据结构(字符串)【蓝桥杯】
字符串
一系列字符,用单引号或者双引号括起
Python不支持单字符类型,单个字符也被看作为字符串,许多用法与List一致
访问字符串中的元素:使用方括号+下标(从0开始)
切片:s[start🔚stop],在字符串s下标为(start,end)中,步长为stop
len(s):求字符串的长度
+:字符串连接
*:重复字符串
in、not in:存在、不存在
str(x):把x强制转换成字符串
a = 123
s = str(a)
print("s = ",type(s))
print(int(s))
输出
s = <class 'str'>
123
字符串简介--转义字符
转义字符是以反斜杠(\)开头的特殊字符,用于表示不能直接键入的字符,例如换行符,制表符,引号和反斜杠本身

\\
s = "hellohelloo\\world"
print(s)输出
hellohelloo\world\"
s = "hellohelloo\"world"
print(s)
输出
hellohelloo\world\n
s = "hellohelloo\n\nworld"
print(s)输出
hellohelloo
world\t
s = "hellohelloo\t\tworld"
print(s)输出
hellohelloo world字符串简介–ord和chr
python将字符编码成Unicode码:简单理解为所有语言的字符(所有、数字中文等所有符号)
字符 =》 Unicode码:ord(x),x为字符,ord(x)为整数
Unicode码 = 》字符:chr(x),x为整数,chr(x)为字符
print(ord('蓝'))
print(ord('桥'))
print(ord('a'))
print(ord('b'))
print(chr(34013))
print(chr(26725))
print(chr(97))
print(chr(98))输出
34013
26725
97
98
蓝
桥
a
b小结

字符串常用方法—判断类方法
s = "Hello,World"
print(s.istitle())
s = "Hello World"
print(s.isalpha())输出
True
False字符串常用方法—转换类方法

s = "hello world"
#把s变成标题字符串
t = s.title().swapcase()
print("t =",t)
print("s =",s)
print('-'*10)
#删除左侧的空格
s = " hello world"
t = s.lstrip()
print("t =",t)
print("s =",s)
print('-'*10)
#删除左侧的多个字符,e、h空格
s = " Hello World"
t = s.lstrip('eh ')
print("t =",t)
print("s =",s)
print('-'*10)
#替换字符
s = "abcd abcd abcd abcd"
t = s.replace('ab', 'AB')
z = s.replace('ab', 'AB', 2)
print("t =",t)
print("z =",z)
print("s =",s)
print('-'*10)
#右对齐
s = "hello"
t = s.rjust(15,'*')
print("t =",t)
print("s =",s)输出
t = hELLO wORLD
s = hello world
----------
t = hello world
s = hello world
----------
t = Hello World
s = Hello World
----------
t = ABcd ABcd ABcd ABcd
z = ABcd ABcd abcd abcd
s = abcd abcd abcd abcd
----------
t = **********hello
s = hello
----------
字符串常用方法—查找类方法

#count()
s = "abcd abcd abcd abcd"
print(s.count('a'))
#find()
s = "Hello World"
print(s.find('o'))
#rfind()输出
4
4字符串常用方法—字符串和List类方法
字符串转换成List(由于字符串本身是不可修改,转换成list可以进行修改)
利用split()方法对字符串进行分割:
str.solit(str=“”,num=string.count(str)):
str表示分隔符,默认为空字符,包括空格,换行,制表符等。
a,b = input().split()
print(int(a)*int(b))输出
123 345
42435转换成列表—简短写法
a = [int(x) for x in input().split()]
print(a)输出
1 2 3 4 5 6 7 8 9
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 豪米
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果


