Python學習筆記4_字符串

字符串操作

字符串基本操作

字符串是序列的一種,所以序列通用的操作,字符串都可以,諸如索引,分片,乘法,自各成員等,需要注意的是字符串屬於不可變序列。

字符串格式化

#使用%進行字符串格式化,最基本用法
name = 'Leon'
sentence = 'My name is %s'
print(sentence % name)

運行結果:

My name is Leon
#使用元組或字典格式化一個以上的值
formatVals = 'Leon',23
sentence2 = 'My name is %s,I\'m %i years old'
print(sentence2 % formatVals)
print("%s is a %s" % ('Lily','girl'))

運行結果:

My name is Leon,I'm 23 years old
Lily is a girl
#使用模版進行字符串格式化[類似於UNIX SHELL裏的變量替換]
from string import Template
t2 = Template('Hi,$name1!I\'m $name2')
str2 = t2.substitute(name1='Lucy',name2='Leon')
print(str2)

運行結果:

Hi,Lucy!I'm Leon
##格式化單詞的一部分
t3 = Template('Hello,${x}ld!')
str3 = t3.substitute(x='wor')
print(str3)

運行結果:

Hello,world!
#使用字典格式進行格式化[safe_substitute爲substitute的安全方式]
t4 = Template('$name is $doing!')
dic4 = {}
dic4['name'] = 'Lily'
dic4['doing'] = 'running'
str4 = t4.substitute(dic4)
print(str4)

運行結果:

Lily is running!

更復雜完整的字符串格式化諸如字段寬度,對齊等。轉換說明:
這裏寫圖片描述
轉換類型:
這裏寫圖片描述

print("PI=%f" % 3.1415)
print("PI=%.3f" % 3.1415)
print("PI=%10.3f" % 3.1415)
print("PI=%-10.3f" % 3.1415)
print("PI=%010.3f" % 3.1415)
print("PI=%+-10.3f" % 3.1415)
print("PI=%+010.3f" % 3.1415)

運行結果:

PI=3.141500
PI=3.142
PI=     3.142
PI=3.142     
PI=000003.142
PI=+3.142    
PI=+00003.142

字符串常用方法:

#字符串常用方法
#1.find. 查找第一個匹配的字符串位置索引,找不到返回-1,可以包含查找起始位置參數
print('chinese people people'.find('peo'))  
print('chinese people people'.find('peo',9))  
#2.join. split的逆操作,用來在隊列中添加元素,隊列元素必須是字符串
seq = ['1','2','3','4','5']
sep = '|'
newstr = sep.join(seq)
print(newstr)
#3.lower. 返回字符串的小寫字母版
print('HELLO WORLD'.lower())
#4.replace. 字符串替換
print('我|是|中國人'.replace('|',' '))
#5. split. 字符串切割,當不提供分割參數時,程序會把所有空格,如空格,製表符,換行等作爲分隔符
print('123,456,789,,,'.split(','))
print('123 456\t789\n123'.split())
#6. strip. 去除字符串兩邊的空格或指定字符
print('  123456  '.strip())
print(' * 1 23456!x  !'.strip(' *!')) #字符串兩邊分別從第一個不是去除字符的位置開始保留字符
#7. translate. 替換字符串的某些部分,只處理單個字符,此函數的使用需要用到轉換表,也可以成爲映射表
str5 = 'hello world'
table = str5.maketrans('abcdefghijklm','AB你好EFGHIJKLM')
print(table)
print(str5.translate(table))

運行結果:

1===================================
8
15
2===================================
1|2|3|4|5
3===================================
hello world
4===================================
我 是 中國人
5===================================
['123', '456', '789', '', '', '']
['123', '456', '789', '123']
6===================================
123456
1 23456!x
7===================================
{97: 65, 98: 66, 99: 20320, 100: 22909, 101: 69, 102: 70, 103: 71, 104: 72, 105: 73, 106: 74, 107: 75, 108: 76, 109: 77}
HELLo worL

總結:

python與java的方法類似卻又不盡相同,python的split函數與java的split相比,python的split截取到最後,而java截取到最後一個不是匹配字符處。如使用兩種語言截取“||0||0|||”,根據|截取,python截取結果爲[”, ”, ‘0’, ”, ‘0’, ”, ”, ”],java截取結果爲[“”, “”, “0”, “”, “0”],且python的split方法可以不提供參數,此時默認以空格,製表符,換行等分割;python的strip方法與java的trim相比,java的功能更精簡,只去掉字符串首位的空格,strip卻要更強大,支持參數輸入進行指定字符刪除。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章