新聞中心
Python中的字符串(str)是用于表示文本數(shù)據(jù)的一種基本數(shù)據(jù)類(lèi)型,字符串可以包含字母、數(shù)字、符號(hào)和空格等字符,在Python中,字符串是不可變的,這意味著一旦創(chuàng)建了一個(gè)字符串,就不能更改它的內(nèi)容。

1、創(chuàng)建字符串
在Python中,有多種方法可以創(chuàng)建字符串:
使用單引號(hào)或雙引號(hào):可以使用單引號(hào)(’)或雙引號(hào)(")來(lái)創(chuàng)建字符串。
s1 = 'hello, world!' s2 = "hello, world!"
使用三引號(hào):可以使用三個(gè)連續(xù)的單引號(hào)或雙引號(hào)來(lái)創(chuàng)建多行字符串。
s3 = ''' hello, world! ''' s4 = """ hello, world! """
使用str()函數(shù):可以使用str()函數(shù)將其他數(shù)據(jù)類(lèi)型轉(zhuǎn)換為字符串。
num = 123 s5 = str(num) # 結(jié)果為 "123"
2、字符串操作
Python提供了許多內(nèi)置的方法來(lái)操作字符串,以下是一些常用的字符串方法:
len():返回字符串的長(zhǎng)度。
s = "hello, world!" print(len(s)) # 輸出:13
lower():將字符串中的所有大寫(xiě)字母轉(zhuǎn)換為小寫(xiě)字母。
s = "Hello, World!" print(s.lower()) # 輸出:"hello, world!"
upper():將字符串中的所有小寫(xiě)字母轉(zhuǎn)換為大寫(xiě)字母。
s = "Hello, World!" print(s.upper()) # 輸出:"HELLO, WORLD!"
split():根據(jù)指定的分隔符將字符串分割為一個(gè)列表。
s = "apple,banana,orange"
print(s.split(",")) # 輸出:['apple', 'banana', 'orange']
join():使用指定的字符串將列表中的元素連接成一個(gè)新字符串。
words = ["apple", "banana", "orange"] s = ",".join(words) print(s) # 輸出:"apple,banana,orange"
replace():將字符串中的某個(gè)子串替換為另一個(gè)子串。
s = "I like cats."
print(s.replace("cats", "dogs")) # 輸出:"I like dogs."
find():查找子串在字符串中首次出現(xiàn)的位置,如果找不到,則返回1。
s = "hello, world!"
print(s.find("world")) # 輸出:7
startswith():檢查字符串是否以指定的子串開(kāi)頭。
s = "hello, world!"
print(s.startswith("hello")) # 輸出:True
endswith():檢查字符串是否以指定的子串結(jié)尾。
s = "hello, world!"
print(s.endswith("!")) # 輸出:True
strip():去除字符串首尾的空白字符(包括空格、換行符和制表符)。
s = " hello, world! " print(s.strip()) # 輸出:"hello, world!"
3、格式化字符串
Python提供了多種方法來(lái)格式化字符串,以便在字符串中插入變量值,以下是一些常用的字符串格式化方法:
使用%操作符:可以使用%操作符將變量插入到字符串中。
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age)) # 輸出:"My name is Alice and I am 30 years old."
使用str.format()方法:可以使用str.format()方法將變量插入到字符串中。
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age)) # 輸出:"My name is Alice and I am 30 years old."
使用fstring(Python 3.6+):可以使用fstring在字符串前加上f或F,然后在字符串中使用花括號(hào){}包裹變量名。
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.") # 輸出:"My name is Alice and I am 30 years old."
以上就是關(guān)于Python字符串的基本用法和操作的介紹,希望對(duì)你有所幫助!
本文名稱(chēng):pythonstr用法
標(biāo)題路徑:http://m.fisionsoft.com.cn/article/cosdcsh.html


咨詢(xún)
建站咨詢(xún)
