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

學無先后,達者為師

網站首頁 編程語言 正文

Python中字符串的常用方法總結_python

作者:Mrwhite86 ? 更新時間: 2023-01-02 編程語言

1、strip()、lstrip()、rstrip()

作用:去除兩邊空格、左邊空格、右邊空格

s = "   abcd   "
print("|"+s.strip()+"|")
print("|"+s.lstrip()+"|")
print("|"+s.rstrip()+"|")

查看運行結果:

2、removeprefix()、removesuffix()

作用:移除前綴、移除后綴

s = "hello:world"
print(s.removeprefix("hello"))
print(s.removesuffix("world"))

查看運行結果:

3、replace()

作用:替換字符串中的內容替換成指定的內容

s = "hello:world"
s = s.replace(":", "-")
print(s)

查看運行結果:

4、split()、rsplit()

作用:從左邊起根據對用的內容分割字符串、從右邊起根據對用的內容分割字符串(當指定字符串的分隔次數時存在區別)

s = "hello:world:ok"
print(s.split(":"))
print(s.rsplit(":"))
print(s.split(":", maxsplit=1))
print(s.rsplit(":", maxsplit=1))

查看運行結果:

5、join()

作用:將括號內的元素(均需要滿足字符串格式)合并成一個新的字符串,已join前的字符作為分隔符

l = ["hello", "1", "world"]
print("".join(l))
print("-".join(l))

查看運行結果:

6、upper()、lower()、capitalize()

作用:將所有字母轉為大寫、將所有字母轉為小寫、將首字母轉為大寫

s = "helloWORLD"
print(s.upper())
print(s.lower())
print(s.capitalize())

查看運行結果:

7、islower()、isupper()、isalpha()、isnumeric()、isalnum()

作用:檢查字符串中字母是否都為小寫、檢查字符串中字母是否都為大寫、檢查字符串中字符是否都是字母、檢查字符串中字符是否都是數字、檢查所有的字符串是否都是數字或字母

s1 = "helloworld"
s2 = "OK"
s3 = "hello OK"
s4 = "567"
s5 = "hello123"

print(s1.islower())
print(s2.isupper())
print(s3.islower(), s3.isupper())
print(s1.isalpha())
print(s4.isnumeric())
print(s5.isalpha(), s5.isnumeric())
print(s5.isalnum())
print(s3.isalnum())

查看運行結果:

8、count()

作用:返回指定內容在字符串中出現的次數

s = "hello world"
print(s.count("o"))

查看運行結果:

9、find()、rfind()

作用:返回字符串中是否包含指定內容的索引信息(從左邊開始第一個出現的),不包含時返回-1、返回字符串中是否包含指定內容的索引信息(從右邊開始第一個出現的),不包含時返回-1

s = "hello world"
print(s.find("x"))
print(s.find("o"))
print(s.rfind("o"))

查看運行結果:

10、startswith()、endswith()

作用:檢查字符串是否是以指定內容開頭、檢查字符串是否是以指定內容結束

s = "hello world"
print(s.startswith("h"), s.endswith("h"))
print(s.startswith("d"), s.endswith("d"))

查看運行結果:

11、partition()

作用:有點像find()和split()的結合體。將字符串根據指定的內容拆分為三個元素的元祖,其中第二個元素為指定的內容,如果不包含指定的內容的話,返回的第一個元素為原字符串

s = "hello world"
print(s.partition(" "))
print(s.partition("hello"))
print(s.partition("123"))

查看運行

12、center()、ljust()、rjust()

作用:

返回一個原字符串居中,并使用指定內容(默認為空格)填充至長度width的新字符串

返回一個原字符串左對齊,并使用指定內容(默認為空格)填充至長度width的新字符串

返回一個原字符串右對齊,并使用指定內容(默認為空格)填充至長度width的新字符串。

s = "python"
print(s.center(30))
print(s.center(30, "-"))
print(s.ljust(30, "-"))
print(s.rjust(30, "-"))

查看運行結果:

13、字符串專用f表達式

作用:是格式化字符串的新語法,更易讀,更簡潔,不易出錯,而且速度更快!需要python3.6+的版本支持

name = "bk"
age = 15
print(f"my name is {name},and i am {age} years old!")

查看運行結果:

14、swapcase()

作用:翻轉字符串中的字母大小寫

name = "My Name is Mr.white"
print(name.swapcase())

查看運行結果:

15、zfill()

作用:返回長度為width的字符串,原字符串string右對齊,前面填充0

print("100".zfill(5))
print("+100".zfill(5))
print("-100".zfill(5))
print("+0010".zfill(5))

查看運行結果:

原文鏈接:https://www.cnblogs.com/mrwhite2020/p/16949270.html

欄目分類
最近更新