當前位置:
首頁 >
Python基础(三):字符串和元组常用方法
發布時間:2025/5/22
34
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Python基础(三):字符串和元组常用方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符串
在python中單引號和雙引號所表示的字符串并沒有區別,字符串具有不可變性,及所有操作均不改變原字符串的值。另外三個雙引號和單引號包起來的字符串可以換行寫入。
In [83]: '''sss...: ''...: ss''' Out[83]: "sss\n''\nss"In [84]: """eee...: eee'"'...: """ Out[84]: 'eee\neee\'"\'\n'?
查找
find(object,[start,[stop]])方法,其中參數start和stop為可選參數,代表查找范圍。find()方法在找不到結果會返回-1,而不會報錯,這也是非常重要的一點。
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]: 2index()方法和count()方法與列表使用方法一樣。具體方法可參照上一節https://www.cnblogs.com/austinjoe/p/9365331.html
修改
split(seq=None,maxsplit=-1)方法可以分割字符串,若方法里不加參數默認按空格分割。maxsplit參數可以選擇分割次數,默認是全部分割。
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()方法可以替換字符串中的值為令外一個,還可限制替換次數。
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()方法
這個方法比較重要。列表和元組也可以使用,意義是把該字符串加到可迭代的對象中的每兩個元素之間。
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?
轉載于:https://www.cnblogs.com/austinjoe/p/9365876.html
總結
以上是生活随笔為你收集整理的Python基础(三):字符串和元组常用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单元测试汇总
- 下一篇: Python3 列表的基本操作