如有字符串:
str1 = '192.168.1.1' str2 = 'asdfghjk' str3 = 'Asd fg hj ki' str4 = ' ' str5 = ''
以下是常见操作:
# isalpha()判断字符串是否是字符
>>> res = str1.isalpha() >>> print(res) False
# isalnum()判断是否是数字或者字符组成
>>> res = str1.isalnum() >>> print(res) False
# isdigit()判断是否是整数
>>> res = str1.isdigit() >>> print(res) False
#rfind()从右往左找第一个对应的值,显示的是正向索引,如果没找到匹配的值返回-1
>>> res = str1.rfind('.',0,3) >>> print(res) -1 >>> res = str1.rfind('.') >>> print(res) 9
# find()从左往右找第一个对应的值,显示的是正向索引,如果没找到匹配的值返回-1
>>> res = str1.find('.',0,3) >>> print(res) -1 >>> res = str1.find('.') >>> print(res) 3
# index()从左往右找第一个对应的值,显示的是正向索引,如果没找到匹配的值报错
>>> res = str1.index('.') >>> print(res) 3 >>> res = str1.index('.',0,4) >>> print(res) 3 >>> res = str1.index('.',4,8) >>> print(res) 7 >>> res = str1.index('12') >>> print(res) res = str1.index('12') ValueError: substring not found
# count()显示字符个数,如果没有显示0
>>> res = str1.count('q') >>> print(res) 0 >>> res = str1.count('1') >>> print(res) 4 >>> res = str1.count('1',0,6) >>> print(res) 2 >>> res = str1.count('16') >>> print(res) 1
#把字符串变成抬头(每个单词的开头变成大写,数字不会报错)
>>> res = str1.title() >>> print(res) 192.168.1.1 >>> res = str2.title() >>> print(res) Asdfghjk >>> res = str3.title() >>> print(res) Asd Fg Hj Ki
#判断字符串当中开头字符是否为所选的字符
>>> res = str1.startswith('1') >>> print(res) True >>> res = str2.startswith('A') >>> print(res) False >>> res = str3.startswith('A') >>> print(res) True
#判断字符串当中结尾字符是否为所选的字符
>>> res = str3.endswith('ki') >>> print(res) True >>> res = str3.endswith('j ki') >>> print(res) True >>> res = str3.endswith('jki') >>> print(res) False
#isspace判断是否是由空格组成
>>> res = str3.isspace() >>> print(res) False >>> res = str4.isspace() >>> print(res) True >>> res = str5.isspace() >>> print(res) False
pycharm快捷键
# ctrl + d:复制一行
# ctrl + ?:快速注释一行|撤销
# tab键:缩进4个空格
# shift+tab键:回退4个空格