字符串:編程語言中,用于描述信息的一串字符
字符串的拼接操作
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)
# 整數(shù)占位
s9 = "this goods%% is ¥%d" % 100
print(s9)
# 浮點數(shù)占位
s10 = "圓周率是%.10f" % 13.1415926
print(s10)
字符串函數(shù)笋轨,python系統(tǒng)內置的對字符串的各種操作的支持
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 --查詢指定的字符串出現(xiàn)的位置;如果沒有查詢到返回-1
/ rfind--從右邊開始查詢
index -- 查詢指定的字符串出現(xiàn)的位置驻龟;如果沒有查詢到直接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