文章目录
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. | % |