Day3:Python基础 字符串方法

1、字符串首字母大写

i = "shulei_xiaoxin"
S = i.capitalize()
print(S)
Shulei_xiaoxin

2、字符串全部大写或小写

i = "shuLEI_XIAOxin"
S = i.upper()
S1 = i.lower()
print(S)
print(S1)

SHULEI_XIAOXIN
shulei_xiaoxin

3、不区分大小写验证码

i = "shuLEI_XIAOxin"
VER_CODE = input("请输入验证码,不区分大小写:")

if i.upper() == VER_CODE.upper():
    print("验证成功,欢迎登录~~~")
else:
    print("验证不成功,欢迎下次登录~~")

4、大小写反转

i = "shuLEI_XIAOxin"
S = i.swapcase()
print(S)
SHUlei_xiaoXIN

5、首字符及特殊字符、数据后的字符大写

i = "shuLEI**_XIAO11234xi3n"
S = i.title()
print(S)
Shulei**_Xiao11234Xi3N

6、设置字符长度并居中

i = "shuLEI**_XIAO11234xi3n"
S = i.center(30)
print(S)
    shuLEI**_XIAO11234xi3n    

7、设置字符长,并指定填充字符后居中

i = "shuLEI**_XIAO11234xi3n"
S = i.center(30, "~")
print(S)
~~~~shuLEI**_XIAO11234xi3n~~~~

 8、把字符串中的\t,不足8位的自动补齐8位,大于8位自动补齐16位

i = "shulei\tXIAO11234x\ti3n"
S = i.expandtabs()
print(S)
shulei  XIAO11234x      i3n

9、字符串的公共方法Len

i = "shulei\tXIAO11234x\ti3n"
S = len(i)
print(S)
print(type(S))

21
<class 'int'>

10、检查字符串是否以指定字符开始,返回布尔值

i = "shulei\tXIAO11234x\ti3n"
S = i.startswith("shu")
print(S)
True

11、检查字符串是否以指定字符结尾,返回布尔值

i = "shulei\tXIAO11234x\ti3n"
S = i.endswith("3n")
S1 = i.endswith("3n1")
print(S)
print(S1)

True
False

12、检查字符串指定索引位置否以以指定字符开头/结尾,返回布尔值

i = "shulei\tXIAO11234x\ti3wen"
S = i.startswith("l",3,5)print(S)

True

 13、检查字符串中是否包含指定字符,返回查找字符索引,找不到返回-1

i = "shuleiXIAO11234xi3wen"
S = i.find("l")

print(S)

14、检查字符串中是否包含指定字符,返回查找字符索引,找不到报错

i = "shuleiXIAO11234xi3wen"
S = i.index("lei")

print(S)

15、删除字符串前后空格

i = "    shuleiXIAO11234xi3wen    "
S = i.strip()

print(S)

15、删除字符串中前后的特殊字符

i = "***shuleiXI%%%AO11234xi3we&&n%%%"
S = i.strip("*%&")

print(S)

16、在字符串中统计指定字符的个数

i = "shuleiXiAO11234xi3wen"
S = i.count("i")

print(S)

 17、在字符串转列表

i = "shulei XiAO 1123 4xi3 wen"
S = i.split()

print(S)
['shulei', 'XiAO', '1123', '4xi3', 'wen']

 

 18、在字符串中,指定替换

i = '中华人民共和国中央人民政府,今天成立了,中华人民共和国中央人民政府,今天成立了'
S1 = i.replace('中华', '华夏')
S2 = i.replace('中华','华夏', 1)
S3 = i.replace('中华','华夏', 2)
print(S1)
print(S2)
print(S3)

华夏人民共和国中央人民政府,今天成立了,华夏人民共和国中央人民政府,今天成立了
华夏人民共和国中央人民政府,今天成立了,中华人民共和国中央人民政府,今天成立了
华夏人民共和国中央人民政府,今天成立了,华夏人民共和国中央人民政府,今天成立了

 19、判断字符串是否只有特定字符组成

name = 'Test123'
name1 = 'Test'
name2 = '123456'
print(name.isalnum())
print(name1.isalpha())
print(name2.isdigit())

True
True
True

19、For循环

i = 'asdfasdfasdfadsf'

for loop in i:
    print(loop)

 

posted @ 2022-10-18 09:19  倔犟的石头  阅读(28)  评论(0)    收藏  举报