欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python字符串處理及實現(xiàn)字符串拼接的示例解析

 更新時間:2025年07月18日 08:53:20   作者:曲幽  
文章系統(tǒng)講解Python字符串處理技巧,涵蓋創(chuàng)建、拼接(加號、join、f-string)、切割重組、查找替換、格式化輸出、大小寫與空白處理,最后提供完整數(shù)據(jù)處理模板,感興趣的朋友跟隨小編一起看看吧

Python字符串處理示例解析

一、字符串的"七十二變":創(chuàng)建與切片

Python字符串就像靈活的積木,支持多種創(chuàng)建方式:

# 單雙引號通用
msg = "Hello 數(shù)據(jù)科學家!"
path = r'C:\new_folder'  # 原始字符串避免轉(zhuǎn)義
# 切片操作 [start:end:step]
text = "Python超實用"
print(text[2:5])     # tho
print(text[::-1])    # 用實超nohtyP

二、文本拼接的3把利器

加號拼接:簡單少量文本
join()方法:高效連接列表
f-string:Python 3.6+首選

names = ["張偉", "李娜", "王陽"]
# 傳統(tǒng)方式(性能低)
full_str = names[0] + "," + names[1] + "," + names[2]
# 高效方式
print(",".join(names))  # 張偉,李娜,王陽
# 現(xiàn)代方式(推薦)
print(f"獲獎?wù)撸簕names[0]}、{names[1]}、{names[2]}")

三、切割與重組:split()和join()

這對黃金搭檔處理結(jié)構(gòu)化文本:

# 拆分CSV數(shù)據(jù)
csv_data = "ID,Name,Salary\n101,張三,15000"
rows = csv_data.split('\n')
for row in rows:
    cols = row.split(',')
    print(cols)
# 重組URL路徑
folders = ['img','2024','logo.png']
print('/'.join(folders))  # img/2024/logo.png

四、精準定位:查找替換技巧

find():返回首次出現(xiàn)位置
replace():全局替換內(nèi)容
in關(guān)鍵字:快速存在性檢測

log = "ERROR: File not found [code:404]"
# 定位關(guān)鍵信息
print(log.find("404"))    # 28
print("ERROR" in log)     # True
# 敏感信息脫敏
secure_log = log.replace("404", "XXX")
print(secure_log)  # ERROR: File not found [code:XXX]

五、格式化輸出:三種高階玩法

告別混亂拼接:

# 1. %格式化(經(jīng)典)
print("溫度:%.1f°C" % 23.456)  # 溫度:23.5°C
# 2. str.format()(靈活)
print("坐標:({x},{y})".format(x=120, y=89))
# 3. f-string(推薦)
name = "Alice"
print(f"歡迎{name.upper()}!積分:{1000*1.2:.0f}")

六、清洗標準化:大小寫與空白處理

數(shù)據(jù)清洗必備四件套

raw_text = "  Python數(shù)據(jù)分析  \t\n"

# 去空格
clean_text = raw_text.strip()  
print(clean_text)  # "Python數(shù)據(jù)分析"

# 大小寫轉(zhuǎn)換
print(clean_text.upper())  # PYTHON數(shù)據(jù)分析
print(clean_text.lower())  # python數(shù)據(jù)分析

# 首字母大寫
print("hello world".title())  # Hello World

七、終極武器:完整數(shù)據(jù)處理模板

def clean_text_data(text):
    """文本清洗標準化流程"""
    # 1. 去除首尾空白
    text = text.strip()  
    # 2. 轉(zhuǎn)換為小寫
    text = text.lower()  
    # 3. 替換特殊字符
    text = text.replace('$', 'USD').replace('¥', 'CNY')
    # 4. 分割重組
    words = text.split()
    return ' '.join(words[:5])  # 保留前5個詞
raw_data = "  $19.99 限時優(yōu)惠 買一送一  "
print(clean_text_data(raw_data))  
# 輸出:usd19.99 限時優(yōu)惠 買一送一

python中7種方法實現(xiàn)字符串的拼接

1.直接通過(+)操作符拼接

>>> 'Hello' + ' ' + 'World' + '!'
'Hello World!'

使用這種方式進行字符串連接的操作效率低下,因為python中使用 + 拼接兩個字符串時會生成一個新的字符串,生成新的字符串就需要重新申請內(nèi)存,當拼接字符串較多時自然會影響效率。

2.通過str.join()方法拼接

>>> strlist = ['Hello', ' ', 'World', '!']
>>> ''.join(strlist)
'Hello World!'

這種方式一般常使用在將集合轉(zhuǎn)化為字符串,''.join()其中''可以是空字符,也可以是任意其他字符,當是任意其他字符時,集合中字符串會被該字符隔開。

3.通過str.format()方法拼接

>>> '{} {}!'.format('Hello', 'World')
'Hello World!'

通過這種方式拼接字符串需要注意的是字符串中{}的數(shù)量要和format方法參數(shù)數(shù)量一致,否則會報錯。

4.通過(%)操作符拼接

>>> '%s %s!' % ('Hello', 'World')
'Hello World!'

這種方式與str.format()使用方式基本一致。

5.通過()多行拼接

>>> (
...     'Hello'
...     ' '
...     'World'
...     '!'
... )
'Hello World!'

python遇到未閉合的小括號,自動將多行拼接為一行。

6.通過string模塊中的Template對象拼接

>>> from string import Template
>>> s = Template('${s1} ${s2}!') 
>>> s.safe_substitute(s1='Hello',s2='World')
'Hello World!'

Template的實現(xiàn)方式是首先通過Template初始化一個字符串。這些字符串中包含了一個個key。通過調(diào)用substitute或safe_subsititute,將key值與方法中傳遞過來的參數(shù)對應(yīng)上,從而實現(xiàn)在指定的位置導入字符串。這種方式的好處是不需要擔心參數(shù)不一致引發(fā)異常,如:

>>> from string import Template
>>> s = Template('${s1} ${s2} ${s3}!') 
>>> s.safe_substitute(s1='Hello',s2='World')
'Hello World ${s3}!'

7.通過F-strings拼接

在python3.6.2版本中,PEP 498 提出一種新型字符串格式化機制,被稱為“字符串插值”或者更常見的一種稱呼是F-strings,F(xiàn)-strings提供了一種明確且方便的方式將python表達式嵌入到字符串中來進行格式化:

>>> s1 = 'Hello'
>>> s2 = 'World'
>>> f'{s1} {s2}!'
'Hello World!'

在F-strings中我們也可以執(zhí)行函數(shù):

#學習中遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流群:153708845
>>> def power(x):
...     return x*x
... 
>>> x = 5
>>> f'{x} * {x} = {power(x)}'
'5 * 5 = 25'

而且F-strings的運行速度很快,比%-string和str.format()這兩種格式化方法都快得多。

到此這篇關(guān)于Python字符串處理示例解析的文章就介紹到這了,更多相關(guān)Python字符串處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論