1. 程式人生 > >python中字串拆分與合併——split()、join()、strip()和replace()

python中字串拆分與合併——split()、join()、strip()和replace()

Python3 split()方法

描述

split()通過指定分隔符對字串進行切片,如果引數num 有指定值,則僅分隔 num 個子字串

語法

split()方法語法:

str.split(str="", num=string.count(str))

引數

  • str – 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。
  • num – 分割次數。

返回值

返回分割後的字串列表。

例項

以下例項展示了split()函式的使用方法:

#!/usr/bin/python3

str ="this is string example....wow!!!"print
(str.split())print(str.split('i',1))print(str.split('w'))

以上例項輸出結果如下:

['this','is','string','example....wow!!!']['th','s is string example....wow!!!']['this is string example....','o','!!!']

注:split()分割字串返回的是列表

利用re模組分割含有多種分割符的字串:


import re
a='Beautiful, is; better*than\nugly'
# 四個分隔符為:, ; * \n x= re.split(',|; |\*|\n',a) print(x)

應用

網頁地址解析

#coding=utf-8

str="http://www.runoob.com/python/att-string-split.html"
print("0:%s"%str.split("/")[-1])
print("1:%s"%str.split("/")[-2])
print("2:%s"%str.split("/")[-3])
print("3:%s"%str.split("/")[-4])
print("4:%s"%str.split("/")[-5
]) print("5:%s"%str.split("/",-1)) print("6:%s"%str.split("/",0)) print("7:%s"%str.split("/",1)) print("8:%s"%str.split("/",2)) print("9:%s"%str.split("/",3)) print("10:%s"%str.split("/",4)) print("11:%s"%str.split("/",5))

結果為

0:att-string-split.html
1:python
2:www.runoob.com
3:
4:http:
5:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
6:['http://www.runoob.com/python/att-string-split.html']
7:['http:', '/www.runoob.com/python/att-string-split.html']
8:['http:', '', 'www.runoob.com/python/att-string-split.html']
9:['http:', '', 'www.runoob.com', 'python/att-string-split.html']
10:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
11:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']

處理表格檔案
date.txt檔案如下
1 0.0888 201 36.02 28 0.5885
2 0.1399 198 39.32 30 0.8291

import os
data = []
for lines in open(r"date.dat",'r').readlines():
    lines.strip()
    s = [x for x in lines.strip().split()]
    data.append(s)

print(data)
print(len(data[0]))

Python splitlines()方法

Python splitlines() 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一個包含各行作為元素的列表,如果引數 keepends 為 False,不包含換行符,如果為 True,則保留換行符

str.splitlines([keepends])
keepends – 在輸出結果裡是否去掉換行符(‘\r’, ‘\r\n’, \n’),預設為 False,不包含換行符,如果為 True,則保留換行符。

str1 = 'ab c\n\nde fg\rkl\r\n'
print str1.splitlines();

str2 = 'ab c\n\nde fg\rkl\r\n'
print str2.splitlines(True)

#返回結果
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

join()方法

Python中有join()和os.path.join()兩個函式,具體作用如下:
join(): 連線字串陣列。將字串、元組、列表中的元素以指定的字元(分隔符)連線生成一個新的字串
os.path.join(): 將多個路徑組合後返回

join()方法將列表中的字元元素合併為一個大的字串

一、函式說明
1、join()函式
語法: ‘sep’.join(seq)
引數說明
sep:分隔符。可以為空
seq:要連線的元素序列、字串、元組、字典
上面的語法即:以sep作為分隔符,將seq所有的元素合併成一個新的字串

返回值:返回一個以分隔符sep連線各個元素後生成的字串

2、os.path.join()函式

語法: os.path.join(path1[,path2[,……]])
返回值:將多個路徑組合後返回
注:第一個絕對路徑之前的引數將被忽略

#對序列進行操作(分別使用' '與':'作為分隔符)

>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido


#對字串進行操作

>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o


#對元組進行操作

>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido


#對字典進行操作

>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello


#合併目錄

>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'

strip()方法

Python strip() 方法用於移除字串頭尾指定的字元(預設為空格)。
str.strip([chars])
引數 chars – 移除字串頭尾指定的字元。

str = "0000000this is string example....wow!!!0000000"
print (str.strip( '0' ))

輸出:

this is string example....wow!!!

replace()

描述
Python replace() 方法把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數max,則替換不超過 max 次。

語法
replace()方法語法:

str.replace(old, new[, max])

引數

old – 將被替換的子字串。
new – 新字串,用於替換old子字串
max – 可選字串, 替換不超過 max 次

返回值
返回字串中的 old(舊字串) 替換成 new(新字串)後生成的新字串,如果指定第三個引數max,則替換不超過 max 次。

例項

#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);

輸出:


thwas was string example….wow!!! thwas was really string 
thwas was string example….wow!!! thwas is really string

相關推薦

python字串拆分合併——split()join()strip()replace()

Python3 split()方法 描述 split()通過指定分隔符對字串進行切片,如果引數num 有指定值,則僅分隔 num 個子字串 語法 split()方法語法: str.split(str="", num=string

Python字串的isalnum()方法isalpha()方法isdigit()方法

isalnum()方法 語法: str.isalnum() 作用: 如果字串至少有一個字元並且所有字元都是字母或數字則返回 True,否則返回 False。 isalpha()方法 語法: str.isalpha() 作用: 如果字串至少有一個字元並且所有

Python字串datetime的相互轉換

1. 字串轉換成datetime物件 from datetime import datetime t = datetime.strptime(append_at, '%Y-%m-%d %H:%M:%S') 結果顯示: <class 'datetime.datetime

Python“i+=ii=i+i”的區別梳理:(引用記憶體可變引數不可變引數)

Python中“i+=i與i=i+i”的區別梳理 一、 "i+=i"執行時資料記憶體的變化 當num+=num執行時,num原引用的記憶體空間中,根據空間中儲存的引數的資料型別是否為可變型別而進行變化,***可變的引數資料型別***有:列表、字典;***不可變引

Python字串的find()方法index()方法

find()方法 語法 str1.find(str2, beg=0, end=len(string)) 作用 檢測 str2 是否包含在字串str1中,如果指定範圍 beg 和 end ,則檢查是否包含在指定範圍內,如果包含返回開始的索引值,否則返回-1。 i

python字串分割合併

python字串分割與合併 2018-7-29 字串分割: split_str=str.split() split2_str=str.split(',') ##表示以不同的字串為分割線,對字串拆分,得到列表 字串合併: #將split

python字串:宣告編碼函式格式化

字串的宣告有三種方式:單引號、雙引號和三引號(包括三個單引號或三個雙引號)。例如: ? 1 2 3 4 5 6 7 8 9 10 11 12 >>> str1= 'hello world'  >>> str2= "hello

python字串列表轉換

首先是這樣的,看書的時候書上是這麼寫的: 當時腦子裡只有一個想法,字串轉為字串列表不是用split()嘛,為了解開謎團,就決定試一試,畢竟自己以前從來沒有注意到這個問題。 結果: 的確可以是字串,列表元素是字串字元。看來我真的注意到的問題太少了。。。。。。 補充: 字串變列表: st

Python時間戳時間字串互相轉化

#設a為字串 import time a = "2011-09-28 10:00:00" #中間過程,一般都需要將字串轉化為時間陣列 time.strptime(a,'%Y-%m-%d %H:%M:%S') >>time.struct_time(tm_year

Python字串連線刪除陣列指定元素記錄指令碼執行時間

1、Python中字串連線 a = "I am " b = 20 c = a + '%d'%b '%d'%b將b轉換成為字串格式,”+“對兩個字串進行拼接。 2、刪除陣列中指定元素 Python中陣列的使用:http://blog.163.com/jackylau_v/

Python的encodedecode,詳解字串位元組物件之間的轉換

1.相關異常我們在處理交換的資料時經常遇到這樣的異常:TypeError: can't use a string pattern on a bytes-like objectTypeError: a bytes-like object is required, not 'st

12Python 字串大小寫轉換

簡單總結下Python中字串大小寫轉換,最後有個處理列表的方法感覺有點意思 a = 'hello python' #都是小寫 b = 'Hello python' #第一個字母大寫 c =

python字串split()join()strip()函式的總結

str.split(' ') ——————————————————————————————————————————————————— 1.按某一個字元分割,如‘.’ >>> s

python的可變不可變對象

不想 不可變 ron 中一 再看 += function itl 們的 Python中的可變對象和不可變對象 什麽是可變/不可變對象 不可變對象,該對象所指向的內存中的值不能被改變。當改變某個變量時候,由於其所指的值不能被改變,相當於把原來的值復制一份後再改變,這會

python元組小括號的關系

原來 例如 精簡 blank bsp 元素 lis [0 逗號 在學習Python 的時候。說到有兩種數據類型,一種叫 列表,一種叫做元組,可以認為,元組是功能精簡的列表。因為它少了列表很多功能。但是又有相識。定義他們的時候,主要是用中括號和小括號之分。 例如:定義一個列表

Python運算符while初識

strong spa .cn wid 比較 logs 語法 案例 一個 一、運算符   1、算術運算:   2、比較運算:   3、賦值運算:   4、位運算: 註: ~ 舉例: ~5 = -6 解釋: 將二進制數+1之後乘以-1,即~x = -(x+1),-

Python使用循環語句打印三角形菱形

size 不能 div 16px 作用 blog 部分 == gre 前言:在學習開發語言循環語句的使用過程中,經常會打印各種形狀來驗證對循環語句的熟練掌握程度,接下來就使用python來打印多種形狀練習。 如下示例中:變量i用於控制外層循環(圖形行數),j用於控制空格的個

Python深拷貝淺拷貝區別

分配 img 地址 append 淺拷貝 pen image pre 內容 淺拷貝, list值是可變的,str值不可變,只能重新賦值 a=b=c=‘wjx‘print(a,b,c)c= ‘jmy‘#重新賦值了,所以內存分配了新的地址print(a,b,c)print(id

Python錯誤之 TypeError: object() takes no parametersTypeError: this constructor takes no arguments

obj blog img typeerror str mage 劃線 es2017 http TypeError: object() takes no parameters TypeError: this constructor takes no arguments

Python的strunicode處理方法

text pre def 包括 unicode編碼 response 會有 determine 展示 Python中的str與unicode處理方法 2015/03/25 · 基礎知識 · 3 評論 · Python 分享到:42 原文出處: liuaiqi627