Python中的字符串(str)是用于表示文本數據的一種基本數據類(lèi)型,字符串( ?ω?)可以包含字母、數字、符號和(′_`)空格等字符,在Python中,字符串是不可變的,這意味著(zhù)一旦創(chuàng )建了一個(gè)字符串,就不能更改它的內容。
(圖片來(lái)源網(wǎng)絡(luò ),侵刪)1、創(chuàng )建字符串
在Python中,有多種方法可以創(chuàng )建字符串:
使用單引號或雙引號:可以使用單引號(’)或雙引號(")來(lái)創(chuàng )建字符串。
s1 = 'hello, world!'s2 = "hello, world!??"使用三引號:可以使用三個(gè)連續的單(′▽?zhuān)?引號或雙引號來(lái)創(chuàng )建多行字符串。
s3 = '''hello,world!'''s4 = """hello,world!"&q??u??ot;"使用str()函數:可以使用str()函數將其他數據類(lèi)型轉換為字符串。ヽ(′?`)ノ
num = 123s5 = str(num) # 結果為 "123"??;2、字符串操作
P??ython提供了許多內置的方法來(lái)操作字符串,以下是一些常用的字符串方(fang)法:
len():返回字符串的長(cháng)度。
s = "hello??, world!"p??r┐(′ー`)┌int(len(s)) # 輸出:13
lower():將字符串中的所有大寫(xiě)字母轉換為小寫(xiě)字母。
s = "Hello, World!&qu(′?`)ot;print(s.lower()) # 輸出:"hello, world!"upper():將字符串中的所有小寫(xiě)字母轉換為大寫(xiě)字母。
s = "Hello, World!"print(s.uppe( ???)r()) # 輸出:"HELLO, WORLD!"
split():根據指定的分隔符將字符ヽ(′ー`)ノ串分割為一個(gè)列表。
s = "apple??,banana,orange"print(s.split(",&???quot;)) # 輸出:['apple', 'banana', 'orange']join():使用指ヽ(′▽?zhuān)?ノ定的字符串將列表中的(de)元素連接成一個(gè)新字符串。
words = ["apple", "banana", "orange"]s = ",".join(w(◎_◎;)ords)print(s) # 輸出:"apple,banana,orange"
replace():將字符串中的某個(gè)子串替換為??另一個(gè)子串。
s = "I like ca(′?`)ts."print(s.replace("cats", "dogs")) # 輸出:"I li(╬?益?)ke dogs."find():查找子串(??ヮ?)?*:???在字符串中首次出現的位置,如果找不到,則返回1。
s = "hello, world!"print(s.find("world")) # 輸出:7startswith():檢查字ヽ(′▽?zhuān)?ノ符串是否以指定的子串開(kāi)頭。
s = "hello, world!"print(s.startswith("hello")) # 輸出:Trueendswitヽ(′▽?zhuān)?ノh():檢查字符串是否以指定的子串結??尾。
s = "hello, world!"print(s.endswi??th("!&qヽ(′▽?zhuān)?/uot;)) # 輸出:Truestrip():去除字符串首尾的空白字符(包括空格(╯‵□′)╯、換行符和制表符)。
s = " hello, world! "print(s.strip()) # 輸出:"hello, world!"
3、格式化字符串
Python提供了多種方法來(lái)格式化字符串,以便在字符串中插入變量值,以下是一些常用的字符串格式化方法:
使用%操作符:可以使用%操作符將變量插入到字符串中。
name = "Alice"age = 30print(&qu(′?`)ot;My name is %s and I am %d years old." % (n??ame, age))?? # 輸出:"My name is Alice and I am 30 years old.&??quot;
使用st??r.format()方法:可以使用str.format()方法將變量插入到字符串中。
name = "Alice"age = 30print("(°ロ°) !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,然后在字符串中使用花括號{ }包裹變??量名。
name = &quo( ?° ?? ?°)t;Alice"age = 30print(f"My name?? is { name} an??d I am { age} years old.") # 輸出:"My name is Alice and?? I am 30 years old."以上就是關(guān)于Python字符串的基本用法和操作的介紹,希望對你有所幫助!