Python字符串

字符串:编程语言中,用于描述信息的一串字符

字符串的拼接操作

1.将字符串s重复十次赋值给s1
s = "hello"
s1 = s * 10
print(s1)
2.两个字符串可以直接通过连接符号+拼接

字符串类型不可以和其他类型直接拼接

s1 = "hello"
s2 = "world"
s3 = s1 + s2
4.字符串的特殊拼接:占位符拼接
name = input("请输入您的姓名:")
s5 = "welcome to China, my name is " + name
s6 = "welcome to china, my name is %s" % name
s7 = "hello my name is %s, %s years old!" % (name, 18)
# 整数占位
s9 = "this goods%% is ¥%d" % 100
print(s9)
# 浮点数占位
s10 = "圆周率是%.10f" % 13.1415926
print(s10)
字符串函数,python系统内置的对字符串的各种操作的支持
1.判断大小

capitalize首字母大写 upper大写 lower小写
istitle是否首字母大写 isupper是否大写 islower是否小写

s1 = "Hello"
s2 = "jerry"
s3 = "SHUKE"

print(s1.capitalize(), s1.upper(), s1.lower())
print(s1, s1.istitle(), s1.isupper(), s1.islower())
print(s2, s2.istitle(), s2.isupper(), s2.islower())
print(s3, s3.istitle(), s3.isupper(), s3.islower())
输出:
Hello HELLO hello
Hello True False False
jerry False False True
SHUKE False True False
2.对齐方式和剔除空格
s = "hello"
s.center(10)  # s在操作的时候,占用10个字符,居中对其
s.center(11, '-') # s在操作的时候,占用11个字符,居中对其,空白的位置使用指定的字符补齐
s.ljust(10) # s占用10个字符,左对齐
s.rjust(10) # s占用10个字符,右对齐
s.lstrip() # 删除字符串s左边的空格
s.rstrip() # 删除字符串s右边的空格
s.strip() # 删除字符串s两边的空格
3.字符串的查询、匹配操作

find --查询指定的字符串出现的位置;如果没有查询到返回-1
/ rfind--从右边开始查询
index -- 查询指定的字符串出现的位置;如果没有查询到直接Error
/ rindex -- 从右边开始查询

s = "hello"
x = s.find("lo") 
x2 = s.index("lo")

s.startswith("he") # 判断s是否是"he"开头的字符串吧,返回True/False
s.endswith("lo") # 判断s是否是"lo"结尾的字符串,返回True/False
4.字符串的拆分
img = "https://ww.baidu.com/a/b/c"

# 拆分字符串
print(img.rpartition("/")[-1])
print(img.split("/")[-1])
输出:
c
c
5.字符串的替换
content = "hello world"
print(content)
content = content.replace("orl", "***")
print(content)
输出:
hello world
hello w***d
6.字符串的复杂替换

添加一个映射/对应关系表[a->b b->c c->d]
table = str.maketrans(“abcd”, “bcde”)
完成替换操作
S.translate(table)

s1 = "abcdefghijklmnopqrstuvwxyz"
s2 = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
s = "hello word"
t = str.maketrans(s1,s2)
x = s.translate(t)
print(x)
输出:SVOOL DLIW

你可能感兴趣的:(Python字符串)