python-5-str common operations

Foreword

This section will explain the operation of string str common method, and the for loop.

A, srt common operations

1, the first letter capitalized:

# 1, the first letter capitalized 
S = ' Xiao Long ' 
S1 = s.capitalize ()
 Print (S1)

 2, all uppercase, all lowercase:

# 2, all uppercase, lowercase 
S = ' Xiao Long ' 
S2 = s.upper () 
S21 = s.lower ()
 Print (S2)
 Print (S21)

 3, case-insensitive wording:

# 3、不区分大小写写法
s = 'xiao long'
s_str = 'ABcd'
p = input('请输入验证码,不区分大小写:')
if s_str.upper() == s_str.upper():
    print('验证码正确!')
else:
    print('验证码错误,请重新输入')

4、大小写对换,如A换为a,b换为B:

# 4、大小写对换,如A换为a,b换为B
s = 'Ab'
s3 = s.swapcase()
print(s3)

 5、有间隔(特殊字符或数字隔开)的首字母大写:

# 5、有间隔(特殊字符或数字隔开)的首字母大写
s = 'xiao long'
s4 = s.title()
print(s4)

 6、居中,空白填充:

# 6、居中,空白填充
s = 'xiao long'
s5 = s.center(20, '-')
print(s5)

 7、len,查看长度:

# 7、len,查看长度
s = 'xiao long'
print(len(s))

 8、find 通过元素找索引,找到返回下标,找不到返回-1:

# 8、find 通过元素找索引,找到返回下标,找不到返回-1
s = 'xiao long'
s1 = s.find('l')
print(s1)

9、index,通过元素找索引,找到返回下标,找不到报错:

# 9、index,通过元素找索引,找到返回下标,找不到报错
s = 'xiao long'
s1 = s.index('i')
print(s1)

 10、默认前后去空格,可用来输入账号时有空格可以剔除做到无影响:

# 10、默认前后去空格,可用来输入账号时有空格可以剔除做到无影响。
s = '   xiao long    '
s1 = s.strip()
print(s1)

 11、统计某个元素数量:

# 11、统计某个元素数量
s = 'xiao long'
s1 = s.count('o')
print(s1)

 12、切割,左右分割 str ---> list(所谓说的切片):

# 12、切割,左右分割 str ---> list
s = 'xiao long'
s1 = s.split(' ')
print(s1)

 13、替换:

# 13、替换
s = '123asd2'
s1 = s.replace('2', '')
s2 = s.replace('2', '', 1)     # 1 表示替换 1个,有序的。
print(s1)
print(s2)

QQ交流群:99941785

Guess you like

Origin www.cnblogs.com/gsxl/p/11923991.html