日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python基础(三):字符串和元组常用方法

發(fā)布時(shí)間:2025/5/22 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python基础(三):字符串和元组常用方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

字符串

在python中單引號(hào)和雙引號(hào)所表示的字符串并沒有區(qū)別,字符串具有不可變性,及所有操作均不改變原字符串的值。另外三個(gè)雙引號(hào)和單引號(hào)包起來的字符串可以換行寫入。

In [83]: '''sss...: ''...: ss''' Out[83]: "sss\n''\nss"In [84]: """eee...: eee'"'...: """ Out[84]: 'eee\neee\'"\'\n'

?

查找

find(object,[start,[stop]])方法,其中參數(shù)start和stop為可選參數(shù),代表查找范圍。find()方法在找不到結(jié)果會(huì)返回-1,而不會(huì)報(bào)錯(cuò),這也是非常重要的一點(diǎn)。

In [78]: str1='hello python'In [79]: str1.find('p') Out[79]: 6In [80]: str1.find('z') Out[80]: -1In [81]: str1.find('l',0,2) Out[81]: -1In [82]: str1.find('l',0,3) Out[82]: 2

index()方法和count()方法與列表使用方法一樣。具體方法可參照上一節(jié)https://www.cnblogs.com/austinjoe/p/9365331.html

修改

split(seq=None,maxsplit=-1)方法可以分割字符串,若方法里不加參數(shù)默認(rèn)按空格分割。maxsplit參數(shù)可以選擇分割次數(shù),默認(rèn)是全部分割。

In [85]: str1='hello python hello word!'In [86]: str1.split() Out[86]: ['hello', 'python', 'hello', 'word!']In [87]: str1.split('o') Out[87]: ['hell', ' pyth', 'n hell', ' w', 'rd!']In [88]: str1.split('o',2) Out[88]: ['hell', ' pyth', 'n hello word!']

替換

replace()方法可以替換字符串中的值為令外一個(gè),還可限制替換次數(shù)。

In [91]: str1='hello python hello word!'In [92]: str1.replace('hello','你好') Out[92]: '你好 python 你好 word!'In [93]: str1.replace('hello','你好',1) Out[93]: '你好 python hello word!'In [94]: str1 #str1值并未改變,字符串的不可變性 Out[94]: 'hello python hello word!'

拼接

字符串的拼接是非常有趣的,方法也是很多的,我主要介紹幾種常用的方法。

1.“+”拼接

In [95]: str1='hello'In [96]: str2='python'In [97]: str1+str2 Out[97]: 'hellopython'

2.join()方法

這個(gè)方法比較重要。列表和元組也可以使用,意義是把該字符串加到可迭代的對象中的每兩個(gè)元素之間。

In [98]: str1='***'In [99]: str1.join(['hello','python']) Out[99]: 'hello***python'In [101]: str1.join(('a','s','d')) Out[101]: 'a***s***d'

3.%s占位符

In [102]: str1="%s我是誰?%s" % ('','不知道')In [103]: str1 Out[103]: '喂我是誰?不知道'

4.format字符串格式化

In [104]: str1="{}你好".format('python')In [105]: str1 Out[105]: 'python你好'

元組

元組常用的有count()和index()。使用方法與之前所講的沒有差別。

In [107]: tup1=('a','w','e','r','r','w')In [108]: tup1.count('w') Out[108]: 2In [109]: tup1.index('e') Out[109]: 2

?

轉(zhuǎn)載于:https://www.cnblogs.com/austinjoe/p/9365876.html

總結(jié)

以上是生活随笔為你收集整理的Python基础(三):字符串和元组常用方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。