❶ python字元串常用方法
python字元串常用方法
1. Python字元串拼接(包含字元串拼接數字)
2. Python截取字元串(字元串切片)
3. Python 的len()函數:獲取字元串長度或位元組數
4. Python split()方法:分割字元串
5. Python join()方法:合並字元串
6. Python count()方法:統計字元串出現的次數
7. Python find()方法:檢測字元串中是否包含某子串
8. Python index()方法:檢測字元串中是否包含某子串
9. Python字元串對齊方法(ljust()、rjust()和center())
10. Python startswith()和endswith()方法
11. Python字元串大小寫轉換(3種)函數
12. Python去除字元串中空格(刪除指定字元)的3種方法
❷ Python入門教程08——字元串操作
Python 提供了5個字元串操作符:in、空格、加號、星號和逗號。
字元串是字元的有序集合,可用in 操作符判斷字元串包含關系,例如:
以空格分隔(或者沒有分隔符號)的多個字元串可自動合並,例如:
加號可將多個字元串合並,例如:
星號用於將字元串復制多次以構成新的字元串,例如:
在使用逗號分隔字元串時,會創建字元串組成的元組,例如:
字元串是一個有序的集合,其中的每個字元可通過偏移量進行索引或分片。字元串中的字元按從左到右的順序,偏移量依次為: 0 、 1 、 2 … len-1 (最後一個字元的偏移量為字元串長度減1);或者倒著排,為: -len … -2 、 -1 。索引指通過偏移量來定位字元串中的單個字元,例如:
通過索引可獲得指定位置的單個字元,但不能通過索引來修改字元串。因為字元串對象不允許被修改,例如:
字元串的切片利用索引范圍從字元串中獲得連續的多個字元(即子字元串)。字元串切片的基本格式如下:
表示返回字元串x中從偏移量start開始,到偏移量end之前的子字元串。 start和end參數均可省略,start默認為0,end默認為字元串長度。例如:
默認情況下,切片用於返回字元串中的多個連續字元,可以通過步長參數來跳過中間的字元,其格式如下:
用這種格式切片時,會依次跳過中間step-1個字元,step默認為1。請看如下代碼:
❸ Python入門教程
Python支持五種基本數字類型,其中有三種整形類型。有符號整型 - 長整型、布爾值 浮點值 復數。
Python中字元串被定義為引號之間的字元集合。支持使用成對的單引號或雙引號,三引號(三個連續的單引號或雙引號)可以用來包含特殊字元。使用索引操作符([])和切片操作符([:])可以得到子字元串。索引規則:第一個字元的索引是0,最後一個字元的索引是-1。
加號(+)用於字元串連接運算,星號(*)則用於字元串重復。可以將列表和元組當成普通的「數組」,可以保存任意數量任意類型的Python對象。通過從0開始的數字索引訪問元素。
列表和元組有幾處重要的區別。列表元素用中括弧([])包裹,元素的個數及元素值可以改變。元組用小括弧(())包裹,不可以更改。通過切片元素([]和[:])可以得到子集,這點與字元串使用方法一致。
❹ python字元串操作集合
把字元串變數和字面值連接起來,組成新的字元串。推薦3個方法:
對字元串進行單個字元索引時,無論是從前往後索引,還是從後往前索引,索引序號一定要在范圍內,否則出錯。
對字元串進行切片截取時,採用 str[start:end] 的方式。start,end可以正,可以負。且如果start標識的位置大於等於end標識的位置,則截取字元串為空。start,end超出字元串的極限位置,那麼就用最值。start默認為0,end默認為字元串長度。
一般的基於文本和行字元串處理,使用sed,awk,grep等工具就可以了,這些命令行工具用起來更便捷,但是也沒有python的這些函數強大。比如沒法實現非貪婪模式匹配。如下:
把連續的數字提取出來,其他的字元拋棄
python處理字元串,比linux命令要復雜一些,功能也更強大一些。對於簡單的處理任務,linux命令已經足夠,python為的是一些更復雜的處理操作。如果兩者都會,豈不是更好?
❺ python的turtle怎樣縮放界面吧
turtle.shapesize(5,5,12)
表示垂直方向縮放到原來為5倍,水平方向縮放到原來5倍,外輪廓寬度12
❻ 用python寫一個程序實現字元串壓縮的方法
import
StringIOimport
gzipcompresseddata
=
gzip方式壓縮的字元串(html)compressedstream
=
StringIO.StringIO(compresseddata)gzipper
=
gzip.GzipFile(fileobj=compressedstream)data
=
gzipper.read()
#
data就是解壓後的數據一個簡單的例子1
import
urllib2
2
from
StringIO
import
StringIO
3
import
gzip
4
5
def
loadData(url):
6
request
=
urllib2.Request(url)
7
request.add_header('Accept-encoding',
'gzip')
8
response
=
urllib2.urlopen(request)
9
if
response.info().get('Content-Encoding')
==
'gzip':10
print
'gzip
enabled'11
buf
=
StringIO(response.read())12
f
=
gzip.GzipFile(fileobj=buf)13
data
=
f.read()14
else:15
data
=
response.read()16
return
data
❼ python字元串操作
字元串操作在各個計算機語言中都是比較常見的操作,下面我們對python的字元串操作做下簡單介紹。
一、索引操作
字元串是由一些連續的字元組成,支持索引操作,索引位置從0開始,比如以下代碼會輸出』P『字元:
二、截取子串
字元串也可以像列表那樣給定起始與終止索引生成一個新的子串,比如以下代碼會輸出「Py」:
三、連接操作
多個字元串相加會生成一個新串,比如以下代碼輸出」Love Python「:
四、大小寫轉換
調用字元串的upper與lower方法會分別生成新的大寫和小寫的字元串,比如以下代碼第一個輸出:」I LOVE PYTHON「,第二個輸出:」i love python「:
五、前後綴判斷
調用字元串的startswith與endswith方法可以判斷字元串是否以某個子串開關或者結尾,比如以下會分別列印出 」 python startswith py 「 和 」 python endswith on 「:
六、查找與替換子串
調用find方法可以判斷是否包含某個子串,比如以下代碼會輸出" python contains th" 和 " python doesn't contain he":
調用replace方法可以對字元串進行替換,比如要把"hello world"中的」hello「替換為」world「,以下代碼會輸出:」world world「
七、分隔字元串
如果我們要把一句話按空格分隔為一個一個的單詞要怎麼做呢,這時調用split方法即可,比如以下代碼會把」hello world ni hao「轉換為["hello","world","ni","hao"]:
八、清除前後字元
如果一個字元串前後有空白字元,我們需要去掉,你可以調用字元串的替換方法來做,但更簡單的做法是調用strip方法,比如以下代碼就會去掉兩端的空白字元輸出「hello python」:
九、大小寫對換
如果我們需要把字元串中的小寫轉換為大寫,大寫轉換為小寫,那要怎麼做呢,很簡單,調用下swapcase就可以了,如以下代碼會輸出「 heLLO pYThON 」:
十、字元分類判斷
有很多方法用來判斷一個字元串是否屬於某個分類,比如 isdigit判斷是否是數字,isalpha判斷是否是字母,isalnum判斷是否是字母數字等,如下代碼:
❽ 用python編寫一個字元串壓縮程序(要求為自適應模型替代法)
你好,下面是LZ777自適應壓縮演算法的一個簡單實現,你可以看看
import math
from bitarray import bitarray
class LZ77Compressor:
"""
A simplified implementation of the LZ77 Compression Algorithm
"""
MAX_WINDOW_SIZE = 400
def __init__(self, window_size=20):
self.window_size = min(window_size, self.MAX_WINDOW_SIZE)
self.lookahead_buffer_size = 15 # length of match is at most 4 bits
def compress(self, input_file_path, output_file_path=None, verbose=False):
"""
Given the path of an input file, its content is compressed by applying a simple
LZ77 compression algorithm.
The compressed format is:
0 bit followed by 8 bits (1 byte character) when there are no previous matches
within window
1 bit followed by 12 bits pointer (distance to the start of the match from the
current position) and 4 bits (length of the match)
If a path to the output file is provided, the compressed data is written into
a binary file. Otherwise, it is returned as a bitarray
if verbose is enabled, the compression description is printed to standard output
"""
data = None
i = 0
output_buffer = bitarray(endian='big')
# read the input file
try:
with open(input_file_path, 'rb') as input_file:
data = input_file.read()
except IOError:
print 'Could not open input file ...'
raise
while i < len(data):
#print i
match = self.findLongestMatch(data, i)
if match:
# Add 1 bit flag, followed by 12 bit for distance, and 4 bit for the length
# of the match
(bestMatchDistance, bestMatchLength) = match
output_buffer.append(True)
output_buffer.frombytes(chr(bestMatchDistance >> 4))
output_buffer.frombytes(chr(((bestMatchDistance & 0xf) << 4) | bestMatchLength))
if verbose:
print "<1, %i, %i>" % (bestMatchDistance, bestMatchLength),
i += bestMatchLength
else:
# No useful match was found. Add 0 bit flag, followed by 8 bit for the character
output_buffer.append(False)
output_buffer.frombytes(data[i])
if verbose:
print "<0, %s>" % data[i],
i += 1
# fill the buffer with zeros if the number of bits is not a multiple of 8
output_buffer.fill()
# write the compressed data into a binary file if a path is provided
if output_file_path:
try:
with open(output_file_path, 'wb') as output_file:
output_file.write(output_buffer.tobytes())
print "File was compressed successfully and saved to output path ..."
return None
except IOError:
print 'Could not write to output file path. Please check if the path is correct ...'
raise
# an output file path was not provided, return the compressed data
return output_buffer
def decompress(self, input_file_path, output_file_path=None):
"""
Given a string of the compressed file path, the data is decompressed back to its
original form, and written into the output file path if provided. If no output
file path is provided, the decompressed data is returned as a string
"""
data = bitarray(endian='big')
output_buffer = []
# read the input file
try:
with open(input_file_path, 'rb') as input_file:
data.fromfile(input_file)
except IOError:
print 'Could not open input file ...'
raise
while len(data) >= 9:
flag = data.pop(0)
if not flag:
byte = data[0:8].tobytes()
output_buffer.append(byte)
del data[0:8]
else:
byte1 = ord(data[0:8].tobytes())
byte2 = ord(data[8:16].tobytes())
del data[0:16]
distance = (byte1 << 4) | (byte2 >> 4)
length = (byte2 & 0xf)
for i in range(length):
output_buffer.append(output_buffer[-distance])
out_data = ''.join(output_buffer)
if output_file_path:
try:
with open(output_file_path, 'wb') as output_file:
output_file.write(out_data)
print 'File was decompressed successfully and saved to output path ...'
return None
except IOError:
print 'Could not write to output file path. Please check if the path is correct ...'
raise
return out_data
def findLongestMatch(self, data, current_position):
"""
Finds the longest match to a substring starting at the current_position
in the lookahead buffer from the history window
"""
end_of_buffer = min(current_position + self.lookahead_buffer_size, len(data) + 1)
best_match_distance = -1
best_match_length = -1
# Optimization: Only consider substrings of length 2 and greater, and just
# output any substring of length 1 (8 bits uncompressed is better than 13 bits
# for the flag, distance, and length)
for j in range(current_position + 2, end_of_buffer):
start_index = max(0, current_position - self.window_size)
substring = data[current_position:j]
for i in range(start_index, current_position):
repetitions = len(substring) / (current_position - i)
last = len(substring) % (current_position - i)
matched_string = data[i:current_position] * repetitions + data[i:i+last]
if matched_string == substring and len(substring) > best_match_length:
best_match_distance = current_position - i
best_match_length = len(substring)
if best_match_distance > 0 and best_match_length > 0:
return (best_match_distance, best_match_length)
return None