一、字符串處理
字符串是計算機程序中最常用的數據類型之一,Python提供了豐富的字符串處理函數和方法,下面將介紹其中幾個常用的。
1.字符串拼接
Python中使用“+”符號進行字符串拼接。
str1 = 'Hello' str2 = 'World' print(str1 + ' ' + str2) # 輸出 Hello World
2.字符串分割
Python中使用split()函數對字符串進行分割,可以指定分隔符。
str3 = 'apple,orange,banana' lst = str3.split(',') print(lst) # 輸出 ['apple', 'orange', 'banana']
3.字符串替換
Python中使用replace()函數進行字符串替換。
str4 = 'I love Python' new_str4 = str4.replace('Python', 'Java') print(new_str4) # 輸出 I love Java
二、字典處理
字典是Python中的一種內置數據類型,也稱為“映射”或“關聯數組”,可以在其中存儲各種類型的對象,包括字符串、數值、元組等。
1.字典的定義和訪問
字典使用大括號{}定義,使用key-value對存儲數據(key和value之間用冒號:分隔),可以使用中括號[]和key訪問對應的value。
dict1 = {'name': 'Tom', 'age': 18} print(dict1['name']) # 輸出 Tom
2.字典的遍歷
Python中使用for循環遍歷字典中的所有key(或value)。
dict2 = {'a': 1, 'b': 2, 'c': 3} for key in dict2: print(key + ': ' + str(dict2[key]))
3.字典的更新和刪除
Python中可以使用update()函數對字典進行更新,使用del語句刪除字典中的鍵值對。
dict3 = {'a': 1, 'b': 2} dict3.update({'c': 3}) print(dict3) # 輸出 {'a': 1, 'b': 2, 'c': 3} del dict3['c'] print(dict3) # 輸出 {'a': 1, 'b': 2}
三、綜合實例
下面給出一個字符串和字典的綜合實例——統計一段英文文本中出現次數最多的單詞。
str5 = "Python is a powerful programming language, capable of many different styles of programming." str5 = str5.lower() # 統一轉換為小寫字母 words = str5.split() # 將字符串按空格分割為單詞列表 dict4 = {} for word in words: if word not in dict4: dict4[word] = 1 else: dict4[word] += 1 max_word = '' max_count = 0 for word, count in dict4.items(): if count > max_count: max_word = word max_count = count print("最多出現的單詞是:", max_word, ",出現了", max_count, "次。")
總結
本文介紹了Python中常見的字符串和字典處理方法,包括字符串的拼接、分割和替換,字典的定義、訪問、遍歷、更新和刪除。實例展示了如何使用這些方法對英文文本進行單詞統計。
原創文章,作者:HFMVG,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/316463.html