日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?字符串常用方法超詳細梳理總結_python

作者:hacker707 ? 更新時間: 2022-05-19 編程語言

python基礎之字符串常用方法???

持續更新python基礎知識,歡迎各位來訪~???

字符串是什么?

字符串就是一系列字符。字符串屬于不可變序列,在python中,用引號包裹的都是字符串,其中引號可以是單引號,雙引號,也可以是三引號(單,雙引號中的字符必須在一行,三引號中的字符可以分布在多行)

txt = 'hello world' # 使用單引號,字符串內容必須在一行
txt1 = "hello python world " # 使用雙引號,字符串內容必須在一行
# 使用三引號,字符串內容可以分布在多行
txt2 = '''life is short
i use python '''

字符串常用方法

1.find()

定義 find()方法返回該元素最小索引值(找不到返回-1) ?舉個栗子?返回"python"的最小索引值

txt = "hello python world."
res = txt.find("python")
print(res)

運行結果如下:

6

2.index()

定義 index()方法返回該元素最小索引值(找不到元素會報錯) ?舉個栗子?返回"world"的最小索引值

txt = "hello python world."
res = txt.index("world")
print(res)

運行結果如下:

13

3.startswith()

定義 startswith() 方法如果字符串以指定值開頭,返回True,否則返回False ?舉個栗子?判斷字符串是不是以"hello"開頭

txt = "hello python world."
res = txt.startswith("hello")
print(res)

運行結果如下:

True

4.endswith()

定義 endswith() 方法如果字符串以指定值結束,返回True,否則返回False ?舉個栗子?判斷字符串是不是以"hello"結束

txt = "hello python world."
res = txt.endswith("hello")
print(res)

運行結果如下:

Flase

5.count()

定義 count() 方法返回指定值在字符串中出現的次數。 ?舉個栗子?統計"o"出現次數

txt = "hello python world."
res = txt.count("o")
print(res)

運行結果如下:

3

6.join()

定義 join() 方法獲取可迭代對象中的所有項目,并將它們連接為一個字符串。必須將字符串指定為分隔符 ?舉個栗子?使用"-"作為分割符,將列表中的所有項連接到字符串中

res = ['h','e','l','l','o']
print('-'.join(res))

運行結果如下:

h-e-l-l-o

7.upper()

定義 upper()方法將字符串全部轉為大寫 ?舉個栗子?將字符串"hello python world"全部轉為大寫

tet = "hello python world"
res = txt.upper()
print(res)

運行結果如下:

HELLO WORLD

8.lower()

定義 lower()方法將字符串全部轉為小寫 ?舉個栗子?將字符串"HELLO PYTHON WORLD"全部轉為小寫

tet = "HELLO PYTHON WORLD"
res = txt.lower()
print(res)

運行結果如下:

hello python world

9.split()

定義 split()方法以指定字符分割字符串,并返回列表 ?舉個栗子?以?號作為分隔符,分割字符串

txt = "hello?python?world"
res = txt.split("?")
print(res)

運行結果如下:

['hello', 'python', 'world']

?擴展?分割后打印還是原字符串(字符串是不可變類型,分割操作是復制一份原字符串,更改的是復制出來的那一份)

txt = "hello?python?world"
res = txt.split("?")
# 打印分割后的
print(res)
# 打印原字符串
print(txt)
['hello', 'python', 'world']
hello?python?world

10.strip()

定義 strip()方法刪除字符串兩端的空格 ?舉個栗子?刪除hello兩端的空格

txt = "    hello  "
res = txt.strip()
print(res)

運行結果如下:

hello

11.replace()

定義 replace()方法以指定內容替換掉被指定內容(默認替換全部,可指定替換次數) ?舉個栗子?以java替換python

txt = 'hello python world'
res = txt.replace('python','java')
print(res)

運行結果如下:

hello java world

?擴展?替換后打印還是原字符串(字符串是不可變類型,替換操作是復制一份原字符串,更改的是復制出來的那一份)

txt = 'hello python world'
res = txt.replace('python','java')
# 打印替換后的
print(res)
# 打印原字符串
print(txt)

hello java world
hello python world

以上就是字符串常用的方法整理

原文鏈接:https://blog.csdn.net/xqe777/article/details/123222475

欄目分類
最近更新