文章目录
- 字符串
-
- 常用函数及操作
-
- capitalize
- lower
- swapcase
- upper
- zfill
- startswith和endswith
- find和index
- strip、lstrip、rstrip
- replace
- bool集合
- 字符串格式化三种方法
-
- 根据类型定义的格式化
- 字符串格式化函数format
- f-strings
- 转义字符
字符串
常用函数及操作
capitalize
name = 'dJk'
new_name = name.capitalize()
print (new_name)
>>>Djk
lower
name = 'DD jj Kk'
new_name = name.lower()
print (new_name)
>>>dd jj kk
swapcase
name = 'DD jj Kk'
new_name = name.swapcase()
print (new_name)
>>>dd JJ kK
upper
name = 'DD jj Kk'
new_name = name.upper()
print (new_name)
>>>DD JJ KK
zfill
name = 'DD jj Kk'
new_name = name.zfill(10)
print (new_name)
>>>00DD jj Kk
startswith和endswith
print ("djk".startswith("dj"))
print ("ddd jjj kk".endswith("j"))
>>>True
>>>False
find和index
print ('my name is djk'.find ('d'))
print ('my name is djk'.index ('k'))
print ('my name is djk'.find ('ddd'))
>>>11
>>>13
>>>-1
strip、lstrip、rstrip
info = ' my name is djk '
new_info = info.strip()
print (new_info)
name = 'djkasdajk'
new_name = name.lstrip('djk')
new_name1 = name.rstrip ('jk')
print (new_name, new_name1)
>>>my name is djk
>>>asdajk djkasda
replace
name = 'hello djk'.replace ('djk', 'ymj')
print (name)
print ('hello djk'.replace ('l', '0', 1))
>>>hello ymj
>>>he0lo djk
bool集合
print (' '.isspace())
print ('djk '.isspace())
>>>True
>>>False
print ('Hello Djk'.istitle())
print ('hello Djk'.istitle())
>>>True
>>>False
print ("DDDWQQ".isupper())
print ("dddd".islower())
>>>True
>>>True
字符串格式化三种方法
根据类型定义的格式化
info = 'my name is %s my age is %s' % ('djk', 10)
print (info)
>>my name is djk my age is 10
info1 = 'my name is %s my age is %s'
name = 'djk'
age = 18
print (info1 % (name,age))
>>my name is djk my age is 18
dict = {'a':'a', 'b':'b'}
print ('dict is %s' % dict)
>>dict is {'a': 'a', 'b': 'b'}
字符串格式化函数format
print('{name}在{option}'.format(name="谢某人",option="写代码"))
print('name={} path={}'.format('zhangsan', '/')
print('{1}在{0}'.format('写代码','谢某人'))
print('{0}在{1}'.format('谢某人','写代码'))
print('{:.2f}'.format(3.14159))
print('{:.5f}'.format(3.14))
print('{:b}'.format(20))
print('{:o}'.format(20))
print('{:d}'.format(20))
print('{:x}'.format(20))
'''
10100
24
20
14
'''
f-strings
name = 'djk'
age = 18
print ('my name is {name} my age is {age}')
print (f'my name is {name} my age is {age}')
>>>my name is {name} my age is {age}
>>>my name is djk my age is 18
转义字符
符号 |
说明 |
\n |
换行 |
\t |
横向制表符 |
\v |
纵向制表符 |
\a |
响铃 |
\b |
退格符 |
\r |
回车 |
\f |
翻页 |
\’ |
转义单引号 |
\" |
转义双引号 |
\\ |
转义斜杠 |