字符串相关方法

1.in   not in  判断某个东西是否在某个东西里面包含
  
name = "你好啊"

if "任啊" in name :
    print('OK')
else:
    print('Error')

2.方法 title()与方法 upper()

s1 = 'alex'
s2 = 'root'
s1.title() #首字母大写
s1.upper() #将字符串中的小写字母转为大写字母
print(s1.upper())
print(s1.title())

 3.将字符串转换为数字,且输出 其类型type()

a = "123"
print(type(a),a)
b = int(a)
print(type(b),b)

 4.字符串首字母大写方法capitalize()

test = "alex"
 # 首字母大写 capitalize()
v = test.capitalize()
print(v)

 5.方法center(20 '"*") #参数后面的星号可有可无 

test = 'alex'
v = test.center(20,"*")# 设置宽度,并将内容居中,20 代指总长度* 空白未知填充,一个字符,可有可无
print(v)

 6.方法count() 表示去字符串中寻找,寻找子序列的出现次数,可以设置起始位置,和结束位置

test = "alexalex"
v = test.count("ex",2,7)
print(v)

 7. format(*args, **kwargs):  格式化,将一个字符串中的占位符替换为指定的值

test = 'i am {name},age {age}'
v = test.format(name= 'alex',age = 20)
print(v)

 8.方法isprintable()   #判断是否存在不可显示的字符,

test = "dasda
sd"
v = test.isprintable()
print(v)

 9.join(self, *args, **kwargs): 

方法 join()将字符串中的每一个元素按照指定的分隔符进行拼接
test = "你是风儿我是沙"
print(test)
v = "..." .join(test) #其中双引号里面的可以是 空格、下划线等等
print(v)

 输出结果如下:

 10.方法lower() 与islower()  #lower () 

test = "alex"
v1 = test.islower()#判断字符串是否全部为小写
v2 = test.lower() #转换字符串中所有大写字符为小写 ;
print(v1,v2)

输出结果如下:

  11. strip方法语法 str.strip([chars]);  其中参数chars 为chars -- 移除字符串头尾指定的字符序列

# 用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
str = "00000003210Runoob01230000000";
print(str.strip('0'))  # 去除首尾字符 0

str2 = "   Runoob      "  # 去除首尾空格
print (str2.strip())
str3 ="	sdnadnasdszcz
" #去除首尾制表符和换行符
print(str3.strip())

输出结果:

12. replace()方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

 replace()方法语法:str.replace(old, new[, max])

  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次

 返回值:返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

#replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str = "www.w3cschool.cc"
print ("菜鸟教程旧地址:", str)
print ("菜鸟教程新地址:", str.replace("w3cschool.cc", "runoob.com"))

str = "this is string example....is wow is !!!"
print (str.replace("is", "was", 3))  #替换is 为was 不超过3次 ,即最后一个is 不会被替换   

输出结果:

 重点为这以下七个方法:

join # '_'.join("asdfasdf")
# split
# find
# strip
# upper
# lower
# replace

原文地址:https://www.cnblogs.com/renzhiqiang/p/10560368.html