str是Python中的一種常見數據類型,代表“字符串”(string)類型,即由若干個字符組成的文本序列。在Python中,字符串是不可變的(immutable),也就是說,一旦創建後就不能再被修改了,只能通過創建新的字符串來操作。接下來,我們將從多個方面對str的特點進行詳細闡述。
一、str的創建
字符串在Python中可以通過單引號、雙引號、三個單引號或三個雙引號來創建。其中,單雙引號創建的字符串沒有區別,三個引號用來創建多行的字符串,其內部可以包含換行符。
str1 = 'hello world!' str2 = "hello world!" str3 = '''hello world!'''
除了使用直接賦值創建字符串之外,還可以使用str()函數將其他類型的值轉為字符串類型,例如:
num1 = 123 num2 = 4.56 str_num1 = str(num1) # '123' str_num2 = str(num2) # '4.56'
在Python 3.x中,字符串默認使用Unicode編碼,因此可以直接使用中文字符,例如:
chinese_str = '你好,世界!'
二、str的操作
1. 字符串連接
使用“+”運算符可以將兩個字符串連接起來:
str1 = 'hello' str2 = 'world' str3 = str1 + str2 # 'helloworld'
2. 字符串重複
使用“*”運算符可以將一個字符串重複n次:
str1 = 'hello' str2 = str1 * 3 # 'hellohellohello'
3. 字符串截取
可以使用索引(從0開始)或切片來獲取字符串的子串。例如:
str1 = 'hello world' char1 = str1[0] # 'h' char2 = str1[-1] # 'd' substr1 = str1[0:5] # 'hello' substr2 = str1[6:] # 'world' substr3 = str1[-5:-1] # 'worl'
4. 字符串長度
可以使用len()函數獲取字符串的長度:
str1 = 'hello world' length = len(str1) # 11
5. 字符串查找
可以使用find()函數或index()函數在字符串中查找子串,並返回其第一次出現的位置(如果不存在則返回-1):
str1 = 'hello world' pos1 = str1.find('o') # 4 pos2 = str1.index('world') # 6 pos3 = str1.find('hi') # -1
6. 字符串替換
可以使用replace()函數替換字符串中的子串:
str1 = 'hello world' new_str1 = str1.replace('world', 'python') # 'hello python'
三、str的格式化
字符串格式化是將一個或多個值插入到字符串中的過程,通常會使用佔位符(也稱為格式化指示符)來指定應該被替換的值的類型和格式。在Python中,字符串格式化可以通過以下方式進行:
1. 使用佔位符
使用“%”運算符來作為佔位符,例如:
str1 = 'hello %s' % 'world' str2 = 'pi is equal to %.2f' % 3.14159
佔位符的類型和格式規範如下:
類型 | 描述 | 示例 |
---|---|---|
%d | 有符號十進制整數 | 123 |
%u | 無符號十進制整數 | 123 |
%f | 浮點數 | 3.14 |
%e | 科學計數法表示的浮點數 | 1.23e+4 |
%g | 浮點數或科學計數法表示的浮點數(自動選擇) | 3.14或1.23e+4 |
%c | 單個字符 | ‘a’ |
%s | 字符串 | ‘hello’ |
%x | 十六進制整數 | 0x12ab |
%% | 表示“%”字符 | ‘%’ |
2. 使用f字符串
在Python 3.6及以上版本中,可以使用f字符串(也稱為格式化字符串)來簡化字符串格式化的過程,例如:
name = 'Alice' age = 18 fstr = f'My name is {name}, I am {age} years old.'
f字符串在大括號中可以直接使用變量名,也可以進行簡單運算和調用函數。
四、str的方法
除了前面提到的字符串操作之外,str還定義了許多常用的方法,例如:
1. upper()和lower()
返回字符串的大寫或小寫形式:
str1 = 'hello world' new_str1 = str1.upper() # 'HELLO WORLD' new_str2 = str1.lower() # 'hello world'
2. strip()和lstrip()和rstrip()
返回去除字符串兩端空格後的結果,strip()表示去除兩端空格,lstrip()表示去除左側空格,rstrip()表示去除右側空格。
str1 = ' hello world ' new_str1 = str1.strip() # 'hello world' new_str2 = str1.lstrip() # 'hello world ' new_str3 = str1.rstrip() # ' hello world'
3. split()
返回將字符串按照指定的分隔符(默認為空格)拆分後的結果:
str1 = 'hello,world' lst1 = str1.split(',') # ['hello', 'world']
4. join()
返回使用指定字符串將一個列表中的元素拼接起來的結果:
lst1 = ['hello', 'world'] str1 = ','.join(lst1) # 'hello,world'
5. count()
返回字符串中指定子串出現的次數:
str1 = 'hello world' count1 = str1.count('l') # 3 count2 = str1.count('world') # 1
還有許多其他有用的方法,例如replace()、find()、index()等,可以查看Python官方文檔(https://docs.python.org/3/library/stdtypes.html#string-methods)進行了解。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/197222.html