python字符串1_3

69 阅读1分钟

9、去掉字符串左右两边的字符 strip 不写默认是空格字符,不管中间的其他的字符

str1 = '         root:12    3   456        '
# root:12    3   456
print(str1.strip())


==========================

str1 = '*****root:12 **   3 *  456****'
# root:12 **   3 *  456
print(str1.strip("*"))

10、字符串的查找

  • find, rfind, index, rindex 查找子字符串在大字符串的哪个位置(起始索引)

    find index 的区别在于找到不时的不一样:find返回-1, index报错

    rfind、rindex返回字符串最后一次出现的位置

    find 返回索引值, 没找到返回-1:

str1 = 'hello python hello python'
# 6
print(str1.find('python'))

# ====================

str1 = 'hello python hello python'
# -1
print(str1.find('java'))
index 返回索引值, 没找到报错:
str1 = 'hello python hello python'
# 报错: ValueError: substring not found
print(str1.index('java'))
  • count: 统计一个子字符串在大字符串中出现的次数
str1 = 'hello python hello python'
# 2
print(str1.count('python'))

11、判断一个字符串里的数据是不是都是数字

isdigit 返回布尔

str1 = '1234355'
# True  必须都是数字才是True  字符串中有 . 也是False
print(str1.isdigit())

12、判断每个元素是不是字母

isalpha 返回布尔

str1 = 'aaa123'
# False
print(str1.isalpha())

13、比较开头的元素是否相同 startswith

str1 = 'hello python'
# True
print(str1.startswith('hello'))

14、比较结尾的元素是否相同 endswith

str1 = 'hello python'
# True
print(str1.endswith('python'))

15、判断字符串中的值是否全是小写的islower

str1 = 'hello python'
# True
print(str1.islower())

16、判断字符串中的值是否全是大写的isupper

str1 = 'hello python'
# False
print(str1.isupper())