新聞中心
在Python中,str 是內(nèi)置的字符串類型,它用于處理文本數(shù)據(jù),字符串是不可變的字符序列,這意味著一旦創(chuàng)建,它們的內(nèi)容就不能更改,Python提供了大量操作字符串的方法和函數(shù),使得字符串的處理變得非常靈活和強(qiáng)大。

成都創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供紅河哈尼網(wǎng)站建設(shè)、紅河哈尼做網(wǎng)站、紅河哈尼網(wǎng)站設(shè)計(jì)、紅河哈尼網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、紅河哈尼企業(yè)網(wǎng)站模板建站服務(wù),十載紅河哈尼做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
以下是一些常用的 str 函數(shù)及其用法:
1、len(string): 返回字符串的長(zhǎng)度(即字符數(shù))。
“`python
text = "Hello, World!"
print(len(text)) # 輸出:13
“`
2、str.lower(): 將字符串中的所有大寫字母轉(zhuǎn)換為小寫。
“`python
text = "Hello, World!"
print(text.lower()) # 輸出:"hello, world!"
“`
3、str.upper(): 將字符串中的所有小寫字母轉(zhuǎn)換為大寫。
“`python
text = "Hello, World!"
print(text.upper()) # 輸出:"HELLO, WORLD!"
“`
4、str.strip(): 刪除字符串開(kāi)頭和結(jié)尾的空白符(包括空格、換行符等)。
“`python
text = " Hello, World! "
print(text.strip()) # 輸出:"Hello, World!"
“`
5、str.split(separator): 使用指定的分隔符將字符串分割成列表。
“`python
text = "Hello, World!"
print(text.split(",")) # 輸出:[‘Hello’, ‘ World!’]
“`
6、str.join(iterable): 使用字符串作為連接符,將可迭代對(duì)象的元素連接成一個(gè)新字符串。
“`python
words = ["Hello", "World"]
print(" ".join(words)) # 輸出:"Hello World"
“`
7、str.replace(old, new): 把字符串中的 old(舊字符串)替換成 new(新字符串)。
“`python
text = "Hello, World!"
print(text.replace("World", "Python")) # 輸出:"Hello, Python!"
“`
8、str.find(sub): 檢測(cè)字符串中是否包含子字符串 sub,如果指定了 start(開(kāi)始位置)和 end(結(jié)束位置),則檢查這個(gè)區(qū)間。
“`python
text = "Hello, World!"
print(text.find("World")) # 輸出:7
“`
9、str.startswith(prefix): 檢查字符串是否以指定的前綴開(kāi)頭。
“`python
text = "Hello, World!"
print(text.startswith("Hello")) # 輸出:True
“`
10、str.endswith(suffix): 檢查字符串是否以指定的后綴結(jié)尾。
“`python
text = "Hello, World!"
print(text.endswith("!")) # 輸出:True
“`
11、str.isdigit(): 如果字符串只包含數(shù)字,返回 True。
“`python
text = "12345"
print(text.isdigit()) # 輸出:True
“`
12、str.format(*args, **kwargs): 格式化字符串,類似于 C 語(yǔ)言中的 printf。
“`python
name = "Alice"
age = 25
print("My name is {0} and I’m {1} years old.".format(name, age)) # 輸出:"My name is Alice and I’m 25 years old."
“`
13、fstring: 在 Python 3.6+ 中,可以使用 fstring 進(jìn)行字符串插值,這是目前推薦的方式。
“`python
name = "Alice"
age = 25
print(f"My name is {name} and I’m {age} years old.") # 輸出:"My name is Alice and I’m 25 years old."
“`
這些只是 str 類提供的一部分功能,由于 str 類是 Python 的核心部分,因此它擁有許多其他方法,可以處理各種復(fù)雜的字符串操作,掌握這些基本的字符串處理方法對(duì)于任何Python程序員來(lái)說(shuō)都是非常重要的。
標(biāo)題名稱:string函數(shù)python
分享地址:http://m.fisionsoft.com.cn/article/cohjppo.html


咨詢
建站咨詢
