字符串(str)
1.strip() 去掉两边空格
string = ' 现在是2018年8月11号下午16点44分 '
print(string)
string = string.strip()
print(string)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
现在是2018年8月 11号下午16点44分
现在是2018年8月 11号下午16点44分
Process finished with exit code 0
2.replace() 替换字符串 参数一是替换前的字符, 参数二是替换后的字符串
string = '现在是2018年8月11号下午16点44分'
print(string)
string = string.replace('4', '6')
print(string)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
现在是2018年8月11号下午16点44分
现在是2018年8月11号下午16点66分
Process finished with exit code 0
3.find() 查找该字符在字符串中的第一个位置的索引
string = '现在是2018年8月11号下午16点44分'
print(string)
result = string.find('在')
print(result)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
现在是2018年8月11号下午16点44分 在
1
Process finished with exit code 0
4.split()分割字符串 可以根据输入的参数对字符串分割放在列表中
string = '1,2,3,4,5'
print(string)
result = string.split(',')
print(result)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
1,2,3,4,5
['1', '2', '3', '4', '5']
Process finished with exit code 0
5. str.join() 拼接 用字符凭借列表,元组等集合里的元素
list1 = ['h', 'e', 'l', 'l', 'o']
list2 = ('hello', 'world')
string = ''.join(list1)
string1 = ','.join(list2)
print(string)
print(string1)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
hello
hello,world
Process finished with exit code 0
6.startswith() 判断某个字符串是不是以某个字符开头,是就返回Ture, 否则返回Flase
string = 'helloworld'
result1 = string.startswith('h')
result2 = string.startswith('e')
print(result1)
print(result2)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
True
False
Process finished with exit code 0
7.endswith() 判断某个字符串是不是以某个字符结尾,是就返回Ture, 否则返回Flase
string = 'helloworld'
result1 = string.endswith('d')
result2 = string.endswith('e')
print(result1)
print(result2)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
True
False
Process finished with exit code 0
8.转换大小写 upper() 函数把小写转换为大写 lower()函数 把大写转换为小写
string = 'helloworld'
string = string.upper()
print(string)
string = string.lower()
print(string)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
HELLOWORLD
helloworld
Process finished with exit code 0
9. capitalize() 函数 是把字符串中的第一个字母变大写,剩余字母变小写
string = 'aBcJ'
string = string.capitalize()
print(string)
结果如下:
D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记十.py
Abcj
Process finished with exit code 0
10.encode() 函数 参数encoding 指定的编码格式编码字符串 errors参数可以指定不同的错误处理方案。
string = 'aBcJ'
result = string.encode(encoding='utf-8', errors='ignore')
# encoding -- 要使用的编码,如"UTF-8"。
# errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。
# 比如有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'