Python中字符串是非常重要的數據類型,在Python中操作字符串是一項基礎工作。字符串操作包括字符串創建、串聯、截取、查找、替換等一系列操作。
一、字符串創建
在Python中使用引號創建字符串,可以使用單引號(’)和雙引號(”)。
str1 = 'Hello World!' str2 = "Python String Manipulation"
創建字符串時需要注意文本中有單引號或雙引號的情況。在這種情況下,我們需要使用轉義字符來標記字符串中的引號。
str3 = 'She said, "I love Python!"' str4 = "Dad asked, \"Did you finish your homework?\""
在Python中也可以使用三重引號(”’或”””)創建多行字符串。
str5 = '''Python is a great programming language. It allows you to do many things in a simple way.'''
二、字符串串聯
在Python中,可以使用加號(+)將兩個字符串連接起來,生成一個新的字符串。
str1 = 'Hello' str2 = 'World' str3 = str1 + ' ' + str2 print(str3) # 輸出:Hello World
還可以使用乘號(*)將一個字符串重複n次。
str4 = 'Python ' str5 = str4 * 3 print(str5) # 輸出:Python Python Python
三、字符串截取
在Python中,可以使用方括號來截取字符串中的部分內容。
str1 = 'Hello World' print(str1[0]) # 輸出:H print(str1[1:5]) # 輸出:ello print(str1[-6:-1]) # 輸出:World
方括號內可以是一個數字,也可以是兩個數字用冒號隔開,表示截取的起始和結束位置。其中帶有冒號表示左閉右開區間。
四、字符串查找
在Python中,可以使用find()函數查找字符串中是否包含指定的子字符串。
str1 = 'Hello World' print(str1.find('Hello')) # 輸出:0 print(str1.find('Python')) # 輸出:-1
如果字符串中包含指定的子字符串,則返回第一個符合條件的位置。如果字符串中不包含指定的子字符串,則返回-1。
還可以使用in關鍵字判斷一個子字符串是否在原字符串中。
str1 = 'Hello World' if 'Hello' in str1: print('字符串中包含Hello') else: print('字符串中不包含Hello')
五、字符串替換
在Python中,可以使用replace()函數將字符串中的指定子字符串替換為另一個字符串。
str1 = 'Hello World' new_str1 = str1.replace('World', 'Python') print(new_str1) # 輸出:Hello Python
replace()函數會返回一個新的字符串,原來的字符串不會改變。
六、字符串格式化輸出
在Python中,可以使用佔位符來對字符串進行格式化輸出。
常見的佔位符:
- %d:整數
- %f:浮點數
- %s:字符串
- %x:十六進制整數
age = 18 print('我今年%d歲。' % age) pi = 3.1415926 print('圓周率約為%f。' % pi) name = 'Tom' print('我叫%s。' % name)
還可以使用format()函數對字符串進行格式化輸出。
age = 18 print('我今年{}歲。'.format(age)) pi = 3.1415926 print('圓周率約為{:.2f}。'.format(pi)) name = 'Tom' print('我叫{0},我今年{1}歲。'.format(name, age))
format()函數可以在佔位符中使用數字來指定使用哪個參數,也可以省略數字按順序使用。
七、字符串常用函數
Python中還有很多常用的字符串函數,在使用時可以通過Python文檔或搜索引擎來查找相關資料。
常用的字符串函數:
- len():返回字符串長度
- upper():將字符串中所有字母轉為大寫
- lower():將字符串中所有字母轉為小寫
- isdigit():判斷字符串是否只包含數字字符
- isalpha():判斷字符串是否只包含字母字符
- startswith():判斷字符串是否以指定字符串開頭
- endswith():判斷字符串是否以指定字符串結尾
str1 = 'Hello World' print(len(str1)) # 輸出:11 print(str1.upper()) # 輸出:HELLO WORLD print(str1.startswith('H')) # 輸出:True print(str1.endswith('ld')) # 輸出:True
八、總結
在Python中,字符串是一種常見的數據類型,字符串操作是程序員必備的基本功之一。本文介紹了字符串的創建、串聯、截取、查找、替換和格式化輸出等操作,以及常用的字符串函數。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/187471.html