python (4)字符串

如果要查看. 后面加的东西要加teb teb

定义变量为字符串的操作

a1="line"
a2="qf"
a3="""hello lenovo"""
a4='''hello world'''
a5="""
hello world
"""
a6='''
hello world
'''

符号型的操作

转义符:\
test='this shirt doesn\'t fit me'  #  ' 有特殊含义
word='hello \nshark'        #这个不是在python里面回车,而是在输入文件后回车
拼接:+ 
print('hello' + 'lenovo')
'lenovo' +1     <报错       #不是同一类型无法拼接
复制:*
print('*' * 20)
********************
print('lenovo 666'*20)  #输出同上面一样重复前面的字符打印
 >>> "hey"  * 0    #字符串 和 0 或者 负数相乘,会得到一个空字符串
''
>>> "hey"  * -100
''
>>>         

split分割

默认空格字符或者tab键

\>>> ip ="192.168.18.18         sdjhf   a;f;l"   #会自定义的删除多余的空格,缩进
>>> ip.split()
['192.168.18.18', 'sdjhf', 'a;f;l']
>--------------------
>>> ip.split(" ")     #用来查看空白字符
['192.168.18.18', '', '', '', '', '', '', '', '', 'sdjhf', '', '', 'a;f;l']      
>-------------------------
自定义分割符
>>> ip.split(".")
['192', '168', '18', '18         sdjhf   a;f;l']

rsplit从右到左分割

从右到左分割,遇到第一个就分割一次;还可以自定义只分割几个

>>> ip.rsplit('.',1)
['192.168.18', '18         sdjhf   a;f;l']   #从右到左分割第一个
>>> ip.rsplit('.',-1)         #从右到左分割全部;负数全分完
['192', '168', '18', '18         sdjhf   a;f;l']

replace替换

>>> url = "www.qfedu.com"
>>> url.replace(".","_")      #把. 替换成_
'www_qfedu_com'
>>> url.replace(".","_",1)   #可以只替换一个
'www_qfedu.com'

strip移除两边的空字符串

>>> s = ' shark '
>>> s.strip()
'shark'
>>> s
' shark '
>>> 
>----------------------------------------
>>> s.split(';')
['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC', '']
>>> s.split(';')[:-1]        #组合前面的字符串切片来看
['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC']

image.png

startswith判断以什么开头的:判断正确错误

>>> s="I went win"
>>> s.startswith("I")
True 
>>> s.startswith("I we")  #可以匹配多个字符
True
>>> s.startswith("we")
False

endswith判断字符串是以什么结尾的

和startswith是差不多的

>>> s ="ah auoh"
>>> s.endswith("d")
False
>>> s.endswith("h")
True

index获取字符串中的索引号

>>> s ="ah auoh"    #有相同的会获取第一个
>>> s.index('h')
1
>>> s = 'hello world'
>>> s.index('h')
0
>>> s.index('l')
2

a.capitalize() #字符串的首字母变大写。其他字母小写
a.title() #单词首字母大写
a.upper() #全部大写
a.lower () #全部小写

交互式输入

n = input(">>>:")  #python3接收到的永远是字符串;python2输入什么接收到的就是什么
print(n)
>------------------------------
>> import getpass         #开启getpass模块
>>> pwd =getpass.getpass("input passwords:")   #getpass里面的getpass函数
input passwords:
>>> print(pwd)
123

对于字符串和字节串类型来说,当且仅当 x 是 y 的子串时 x in y 为 True。
空字符串总是被视为任何其他字符串的子串,因此 "" in "abc" 将返回 True。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。