文章目錄
Python字符串的屬性
- 不可變
- 字符串的每個字符本質也是字符串,因爲python裏面沒有字符(char)類型
- Python3 是Unicode存儲
Pyhon字符串的初始化
a = ""
a = "Hello Python
轉義字符
- r前綴處理轉義字符
- \前面加\
- 三引號裏面可以寫長語句
字符串的索引
- 索引不能超界
Python字符串的方法
- join
- Python的Join方法返回的是全新的字符串
- Python的Join方法是拼接裏面的元素
- Python的Join方法拼接的元素要求是字符串
a = 'abc'
b = '*'.join(a) #join獲得的是一個全新的字符
b
>>>'a*b*c'
a = ['c','d','d']
c = "*".join(a)
c # join連接的是裏面的元素
>>> 'c*d*d'
"*".join(range(5)) # join連接的元素的類型是字符串,如果是數字,會報TypeError類型錯誤
>>> TypeError
"*".join(map(str,range(5)))
>>>'0*1*2*3*4'
- count
count查詢時候,注意: \n是一個字符
Python查找的性能
- 小規模可以用。
- 大規模:字符串找找子串的算法難度非常大;count和index能不用則不用,沒有辦法了可以用
index
PythonTips:index方法和find方法很像,不好的地方在於找不到拋出異常,推薦使用find方法,因爲find方法找不到拋出的是-1,有利於根據返回值做進一步處理。
find和rfind
- find查左邊的
- rfind從右邊的
- find的方法找不到不返回異常,而是會返回異常。我們經常用find返回的結果是否大於0來判斷我們是否找到了子串
- find的子區間
- find效率不高
練習
題目1: 判斷數字並打印,用戶輸入一個十進制正整數:
- 判斷是幾位數
- 打印每一位數字,以及其重複的次數
- 按照個、十、百、千萬… …依次打印每一位數字
#1.1: 判斷是幾位數
len(str_n)
print(f'這個數字的是{len(str_n)}位數')
>>>這個數字的是9位數
#1.2 打印每一位數字,以及其重複的次數
for i in range(-1,-len(str_n)-1,-1):
print(f"該位數是{str_n[i]}," , end="") #打印每一位數字
print(f'它重複了{str_n.count(str_n[i])}次')
>>> >>> >>>
該位數是2,它重複了1次
該位數是3,它重複了2次
該位數是3,它重複了2次
該位數是7,它重複了1次
該位數是8,它重複了1次
該位數是9,它重複了1次
該位數是4,它重複了1次
該位數是5,它重複了1次
該位數是6,它重複了1次
# 題3 按照個、十、百、千萬... ...依次打印每一位數字:
box = ["十兆","兆","千億","百億","十億","億","千萬","百萬","十萬","萬","千","百","個"]
for i in range(-1,-len(str_n)-1,-1):
print()
print(f"該數{box[i]}位數是{str_n[i]}," ) #打印每一位數字
>>> >>> >>>
該數個位數是2,
該數百位數是3,
該數千位數是3,
該數萬位數是7,
該數十萬位數是8,
該數百萬位數是9,
該數千萬位數是4,
該數億位數是5,
該數十億位數是6,
題目2: 判斷數字位數並排序打印
輸入5個十進制正整數,判斷輸入的這些數字分別是幾位數,將這些數字打印且用升序打印
y=list()
for i in range(0,5):
x = int(input("請輸入5個正整數,您在的輸入是"))
print(f"這是一個{len(str(x))}位數")
y.append(x)
print(f"原數列是{y}")
y.sort()
print(f"新升序數列是{y}")
>>> >>> >>>
請輸入5個正整數,您在的輸入是77
這是一個2位數
請輸入5個正整數,您在的輸入是88
這是一個2位數
請輸入5個正整數,您在的輸入是88888
這是一個5位數
請輸入5個正整數,您在的輸入是555
這是一個3位數
請輸入5個正整數,您在的輸入是444
這是一個3位數
原數列是[77, 88, 88888, 555, 444]
新升序數列是[77, 88, 444, 555, 88888]
字符串的分割
split分割
>>> a = "1,2,3,a,b,c"
>>> a
'1,2,3,a,b,c'
>>> a.split() # split立即返回一個列表,不是惰性
['1,2,3,a,b,c']
>>> a.split(",") # 一刀2段
['1', '2', '3', 'a', 'b', 'c']
>>> a.split("3") # 一刀2段,斷點沒了
['1,2,', ',a,b,c']
>>> a.split("9") # 沒切到,就還是一斷
['1,2,3,a,b,c']
>>> b = "\n\t\r\n a\n b\tc\t\n"
>>> b
'\n\t\r\n a\n b\tc\t\n'
>>> print(b)
a
b c
>>> b.split() #缺省分割,開頭結尾的刀,不出空串;儘可能長的默認字符作爲切入點
['a', 'b', 'c']
>>> b.split("\t\n") # 指定的切割
['\n\t\r\n a\n b\tc', '']
>>> b.rsplit()
['a', 'b', 'c']
>>> b.rsplit("\n")
['', '\t\r', ' a', ' b\tc\t', '']
>>> b.rsplit("\n",2) #指定切割次數 與rsplit lsplit配合使用
['\n\t\r\n a', ' b\tc\t', '']
>>> c = b + "d\re"
>>> c
'\n\t\r\n a\n b\tc\t\nd\re'
>>> c.splitlines() # 切掉三種打字機的換行符 切掉 \r \n
['', '\t', ' a', ' b\tc\t', 'd', 'e']
partition
相當於切一刀
>>> d = ",#".join('abcdefg')
>>> d
'a,#b,#c,#d,#e,#f,#g'
>>> d.partition(",") # 立即返回的是三元組(part1,sep,part2),不是列表
('a', ',', '#b,#c,#d,#e,#f,#g')
>>> d.partition(",#") # 接近於 split(",#",1)
('a', ',#', 'b,#c,#d,#e,#f,#g')
>>> d.partition(".")
('a,#b,#c,#d,#e,#f,#g', '', '')
>>> d.rpartition(".")
('', '', 'a,#b,#c,#d,#e,#f,#g')
replace
注意替換指針不回頭
>>> d
'a,#b,#c,#d,#e,#f,#g'
>>> d.replace(',','*') # d變了嗎?當然不可能,因爲,字符串是不可變的
'a*#b*#c*#d*#e*#f*#g'
>>> d.replace(',','*',2) # 可以指定替換次數
'a*#b*#c,#d,#e,#f,#g'
今日順口溜: 一杯二鍋頭 指針不回頭
strip
b
'\n\t\r\n a\n b\tc\t\n'
b.strip()
'a\n b\tc'
b.strip('\n')
'\t\r\n a\n b\tc\t'
b.strip("c \t\n\r") # 包含\t 或者\n連續的都脫掉
'a\n b'
b.rstrip()
'\n\t\r\n a\n b\tc'
首位判斷
效率一般較高
a
'1,2,3,a,b,c'
a.startswith("1")
True
a.endswith("c")
True
a.startswith('abc',4,-1) # 可以指定查找的開始地點和方向
False
Upper和Lower和swapcase
f = "aBbcabc"
f.upper()
'ABBCABC'
a.split(",").pop().upper() #支持鏈式編程
'C'
f.swapcase()
'AbBCABC'
其它:istitle isspace isnumeric isdigit isdecimal isalpha
Python的 C風格格式化字符串
"hi(%d)" % 9
'hi(9)'
50 分鐘了 03-28 上午2 字符串
"hi(%d %d)" %(100,1) #整型
'hi(100 1)'
"hi(%f %f)" %(100,1) #浮點型,默認6
'hi(100.000000 1.000000)'
"hi(%f %.2f)" %(100,1) #浮點型,默認6, 可以定義位數
'hi(100.000000 1.00)'
"hi (%f %s)" % (100,12.1) #%s前面慣例什麼都不加
'hi (100.000000 12.1)'
"hi (%f %s)" % ("100",12.1) # 100這裏一般 不用字符串
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-5f247fe86205> in <module>
----> 1 "hi (%f %s)" % ("100",12.1) # 100這裏一般 不用字符串
TypeError: must be real number, not str
" I am %d years old" %(19)
' I am 19 years old'
"%d*%d=%d" % (2,3,6)
'2*3=6'
"%d*%d=%-4s" % (2,3,6) # 填充對齊
'2*3=6 '
"%d*%d=%4s" % (2,3,6) #對齊
'2*3= 6'
"my name is %s, I am %d" % ("Tom",20)
'my name is Tom, I am 20'
"my name is %(name)s, I am %(age)d" % {"age":20, "name":"Jerry"} #這裏是大括號{}
'my name is Jerry, I am 20'
"%s%%" % 5 # 兩個%,輸出%
'5%'
"%X %X %o %d" % (12,32,93,4) #輸出16進制和8進制
'C 20 135 4'
"%#X %#X %#o %d" % (12,32,93,4) #輸出16進制和8進制
'0XC 0X20 0o135 4'
差值字符串方法
age = 20
name = "Tom"
f"{age}{name}"
'20Tom'
format函數
"{}-{}-{}-{a}-{c}".format(1,2,3,a=100,b=200,c=500)# 按位置傳參,也可以按名稱傳參
'1-2-3-100-500'
"{1}-{0}-{1}-{a}-{c}".format(1,2,3,a=100,b=200,c=500)# 按位置傳參,也可以按名稱傳參
'2-1-2-100-500'
"{}---{}".format(*(1,22)) # format的參數解構,使用星號;很少會這麼寫
'1---22'
class A:
def __init__(self):
self.x = 5
self.y = 6
t = A()
t.x, t.y
(5, 6)
"{0.x}{0.y}".format(t) # 慣例一般不這麼寫,因爲這種寫法寫死了
'56'
"{}{}".format(t.x,t.y) # 慣例這麼寫
'56'
format 浮點數的處理
"{}".format(5.12345678901234567890123456789)
'5.123456789012345'
"{:f}".format(5.12345678901234567890123456789) #默認6位
'5.123457'
"{:9.1f}".format(5.12345678901234567890123456789) #9是前面的空格數,3f 是字符寬度
' 5.1'
"{:<9.1f}".format(5.12345678901234567890123456789) #右對齊 <
'5.1 '
"{:^9.1f}".format(5.12345678901234567890123456789) #居中
' 5.1 '
"{:2f}".format(4.888888888888) #字符寬度大於對齊寬度,一字符寬度優先,即撐爆以保證精度
'4.888889'
"{:10.3%}".format(1/3)
' 33.333%'
"{:#>5}".format(30) #填充字符
'###30'
format時間模塊
import datetime
d1 = datetime.datetime.now()
d1
datetime.datetime(2020, 4, 6, 17, 18, 22, 667515)
"{}".format(d1)
'2020-04-06 17:18:22.667515'
"{0:b}--{0:x}--{0:X}--{0:o}".format(31) #進制轉化,注意如下返回的都是字符串
'11111--1f--1F--37'
"{0:#b}--{0:#x}--{0:#X}--{0:#o}".format(31) #進制轉化,注意如下返回的都是字符串
'0b11111--0x1f--0X1F--0o37'
"{:%Y -%m-%d|-%H - %M -%S }".format(d1)
'2020 -04-06|-17 - 18 -22 '
"{:%y -%h }".format(d1)
'20 -Apr '
"{:%Y/%m/%d %H:%M:%S}".format(d1) #常用建議記憶
'2020/04/06 17:18:22'
Directive | Meaning | Example | Notes |
---|---|---|---|
%a | Weekday as locale’s abbreviated name. | Sun, Mon, …, Sat (en_US); | -1 |
So, Mo, …, Sa (de_DE) | |||
%A | Weekday as locale’s full name. | Sunday, Monday, …, Saturday (en_US); | -1 |
Sonntag, Montag, …, Samstag (de_DE) | |||
%w | Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. | 0, 1, …, 6 | |
%d | Day of the month as a zero-padded decimal number. | 01, 02, …, 31 | |
%b | Month as locale’s abbreviated name. | Jan, Feb, …, Dec (en_US); | -1 |
Jan, Feb, …, Dez (de_DE) | |||
%B | Month as locale’s full name. | January, February, …, December (en_US); | -1 |
Januar, Februar, …, Dezember (de_DE) | |||
%m | Month as a zero-padded decimal number. | 01, 02, …, 12 | |
%y | Year without century as a zero-padded decimal number. | 00, 01, …, 99 | |
%Y | Year with century as a decimal number. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | -2 |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 00, 01, …, 23 | |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, …, 12 | |
%p | Locale’s equivalent of either AM or PM. | AM, PM (en_US); | (1), (3) |
am, pm (de_DE) | |||
%M | Minute as a zero-padded decimal number. | 00, 01, …, 59 | |
%S | Second as a zero-padded decimal number. | 00, 01, …, 59 | -4 |
%f | Microsecond as a decimal number, zero-padded on the left. | 000000, 000001, …, 999999 | -5 |
%z | UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). | (empty), +0000, -0400, +1030 | -6 |
%Z | Time zone name (empty string if the object is naive). | (empty), UTC, EST, CST | |
%j | Day of the year as a zero-padded decimal number. | 001, 002, …, 366 | |
%U | Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. | 00, 01, …, 53 | -7 |
%W | Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. | 00, 01, …, 53 | -7 |
%c | Locale’s appropriate date and time representation. | Tue Aug 16 21:30:00 1988 (en_US); | -1 |
Di 16 Aug 21:30:00 1988 (de_DE) | |||
%x | Locale’s appropriate date representation. | 08/16/88 (None); | -1 |
08/16/1988 (en_US); | |||
16.08.1988 (de_DE) | |||
%X | Locale’s appropriate time representation. | 21:30:00 (en_US); | -1 |
21:30:00 (de_DE) | |||
%% | A literal ‘%’ character. | % |