python中字串常見操作(二)

2022-08-29 20:03:13 字數 2278 閱讀 3533

# 可迭代物件有:字典,列表,元組,字串,集合

str1 = '192.168.1.1'

str2 = 'as df gh jk'

str3 = '小李子'

str4 = ['aa','bb','cc']

str5 = '$$$192.168.1.1&&&'

str6 = '\t\nmysql\t\n'

b = '='

# .join:把可迭代物件轉化為字串

# 字典只迴圈key

# 只能合併裡邊是字串的可迭代物件

>>> res = ''.join(['1','2','3'])

>>> print(res)

123>>> res = ''.join()

>>> print(res)

abc>>> res = ''.join(('1','2','3'))

>>> print(res)

123>>> res = ''.join([1,2,3])

>>> print(res)

res = ''.join([1,2,3])

typeerror: sequence item 0: expected str instance, int found

>>> res = b.join(str4)

>>> print(res)

aa=bb=cc

# splite:是可以把字串分割成列表;rsplit

>>> res = str1.split('.',1)

>>> print(res)

['192', '168.1.1']

>>> res = str1.split('.')

>>> print(res)

['192', '168', '1', '1']

>>> res = str2.split('空格')

>>> print(res)

['as', 'df', 'gh', 'jk']

面試題:

test = "aa ks js \t fa \t ka ",除去\t和空格?

result = test.split()

# replace:替換字串

>>> res = str1.replace('.','|',1)

>>> print(res)

192|168.1.1

>>> res = str1.replace('.','|')

>>> print(res)

192|168|1|1

# strip:去除字串兩邊指定字元,(一般用來除去兩邊特殊字元或格式)

# rstrip(從右邊開始),lstrip(從左邊開始)

>>> res = str5.strip('$&')

>>> print(res)

192.168.1.1

>>> res = str5.rstrip('$&')

>>> print(res)

$$$192.168.1.1

>>> res = str5.lstrip('$&')

>>> print(res)

192.168.1.1&&&

>>> res = str6.lstrip()

>>> print(res)

mysql

# gbk格式的字元編碼:1個中文佔2個位元組

# 用什麼字元編碼寫入就需要用什麼字元編碼格式開啟

#encode和decode分別指編碼和解碼

>>> res = str1.encode('utf-8')

>>> print(res)

b'$$$192.168.1.1&&&'

>>> res = str6.encode('utf-8')

>>> print(res)

b'\t\nmysql\t\n'

>>> res = str3.encode('utf-8')

>>> print(res)

b'\xe5\xb0\x8f\xe6\x9d\x8e\xe5\xad\x90'

>>> res = str3.encode('utf-8')

>>> result = res.decode('utf-8')

>>> print(result)

小李子

#字串可以拼接:相加,可以與數字相乘

# a = '123'

# b = 'abc'

# print(a+b)

python中字串常見操作

mystr hello world,this is python 1 find 檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則返回 1 mystr.find str,start 0,end len mystr mystr hello world,this is python m...

Python字串常見操作

先初始化乙個字串scstring scstring my name is shenchong shen shen find scstring my name is shenchong shen shen print scstring.find shen 輸出結果,第乙個shen的s的角標為11 11...

Python字串常見操作

如有字串mystr hello world hello everyone 以下是常見的操作 1 find與index 檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則find返回 1,index將報錯。返回 str 在 mystr裡面出現的次數,可以指定查詢範圍。把 mystr ...