Python字符串格式化全面学习|学习笔记

简介: 快速学习Python字符串格式化全面学习

开发者学堂课程【Python开发基础入门Python字符串格式化全面学习】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:https://developer.aliyun.com/learning/course/556/detail/7661



内容介绍:

一、字符串

二、字符串定义 初始化

三、字符串元素访问——下标

四、字符串join连接*

五、字符串+连接

六、字符串分割

七、字符串大小写

八、字符串修改

九、字符串查找

十、字符串判断

十一、字符串判断is系列

十二、字符串格式化

十三、字符串练习

 

一、字符串


一个个字符组成的有序的序列,是字符的集合(一个个字符未必是一个字节)

使用单引号、双引号、三引号引住的字符序列

字符串是不可变对象

Python3起,字符串就是Unicode类型

 

二、字符串定义 初始化


举例

s1 = 'string'

s2 = "string2"

s3 = "this's a "String' ‘’’

s4 = 'hello \n magedu.com'

s5 = r"hello \n.magedu.com"

s6 = 'c:\windows\nt'

s7 = R"c:\windows\nt"

s8 = 'c:\windows\\nt'

sql = “””select * from user where name= 'tom' ”””

 

三、字符串元素访问——下标


字符串支持使用索引|访问

sql = "select * from user where name= 'tom ' 

sql[4] #字符串'c'

sql[4] = 'o'

有序的字符集合,字符序列

for C in sql:

print(C)

print(type(C)) #什么类型?

可迭代

lst = list(sql)

 

四、字符串join连接*


"string" .join(iterable)-> str

将可迭代对象连接起来,使用string作为分隔符

可迭代对象本身元素都是字符串

返回一个新字符串

Ist =['1;2','3']

print("\".join(lst)) #分隔符是双引号

print("".join(lst))

print("\n" .join(lst))

lst= ['1',['a','b'],'3']

print(" ".join(lst))

 

五、字符串+连接


+ -> str

将2个字符串连接在一起

返回一个新字符串

 

六、字符串分割


l 分割字符串的方法分为2类

split系

将字符串按照分隔符分割成若干字符串,并返回列表,

partition系

将字符串按照分隔符分割成2段,返回这2段和分隔符的元组

l split(sep= None, maxsplit=-1) -> list of strings

从左至右

sep指定分割字符串,缺省的情况下空白字符串作为分隔符

maxsplit指定分割的次数, -1表示遍历整个字符串

s1 = "I'm \ta super student.'

s1.split()

s1.split('s')

s1.split('super')

s1.split('super ')

s1.split(‘ '),

s1.split(' ',maxsplit=2)

s1.split('\t',maxsplit= 2)

splitlines([keepends]) -> list of strings

Ø 按照行来切分字符串

Ø keepends指的是是否保留行分隔符

Ø 行分隔符包括\n、\r\n、 \r等

'ab c\n\nde fg\rkl\r\n' .splitlines()

'ab c\n\nde fg\rkl\r\n' .splitlines(True)

s1 = "I'm a super student.

You're a super teacher.'

print(s1)

print(s1.splitlines())

print(s1.splitlines(True))

partition(sep) -> (head, sep, tail)

从左至右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾3部分的3三元组;如果没有找到分隔符,就返回头、2个空元素的三元组

sep分割字符串,必须指定

s1 = "I'm a super student."

s1.partition("s')

s1.partition('stu')

s1.partition(")

s1.partition('abc')

rpartition(sep) -> (head, sep, tail)

从右至左,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组:如果没有找到分隔符,就返回2个空元素和尾的三元组

 

七、字符串大小写


upper(

全大写

lower()

全小写

大小写,做判断的时候用

swapcase()

交互大小写

title()-> str

标题的每个单词都大写

capitalize() -> str

首个单词大写

center(width[, fillchar]) -> str

width打印宽度

fillchar 填充的字符

zfill(width)-> str

width打印宽度,居右,左边用0填充

ljust(width[ fillchar])-> str左对齐

rjust(width[ fllchar]) -> str 右对齐

中文用的少,了解一下

 

八、字符串修改


replace(old, new[, count]) -> str

字符串中找到匹配替换为新子串,返回新字符串

count表示替换几次,不指定就是全部替换

www.magedu.com'.replace('w','p')

www.magedu.com'.replace("w','p',2)

www.magedu.com'.replace('w','p',3)

www.magedu.com' .replace('ww'p',2)

www.magedu.com' .replace('www','python',2)

strip([chars])-> str

从字符串两端去除指定的字符集chars中的所有字符

如果chars没有指定,去除两端的空白字符

S = "\r \n \t Hello Python \n \t"

s.strip()

S="Iamveryveryverysorry

s.strip(Iy')

s.strip('Ty )

Istrip([chars]) -> str

从左开始

rstrip([chars])-> str

从右开始

find(sub[, start[, end]) -> int

在指定的区间[start, end) ,从左至右,查找子串sub。找到返回索引,没找到返回-1

rfind(sub[ start[ end]) -> int

在指定的区间[start, end) ,从右至左,查找子串sub。找到返回索引,没找到返回-1

S ="I am very very very sorry"

s.find('very'")

s.find('very', 5)

s.find('very', 6, 13)

s.rfind('very', 10)

s.rfind('very', 10, 15)

s.rfind('very',-10,-1)

 

九、字符串查找


index(sub[, start[ end]) -> int

在指定的区间[start, end) ,从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError

rindex(sub[ start[, end]) -> int

在指定的区间[start, end) ,从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError

S = "I am very very very sorry"

s.index('very')

s.index('very', 5)

s.index('very', 6, 13)

s.rindex('very', 10)

s.rindex('very', 10, 15)

s.rindex('very', -10, -1)

时间复杂度

index和couht方法都是O(n)

随着列表数据规模的增大,而效率下降

len(string)

返回字符串的长度,即字符的个数

count(sub[ start[, end]])-> int

在指定的区间[start, end) ,从左至右,统计子串sub出现的次数

S ="I am very very very sorry"

s.count('very')

s.count('very',5)

s.count('very', 10, 14)

 

十、字符串判断


endswith(suffix[, start[, end]]) -> bool

在指定的区间[start, end) ,字符串是否是suffix结尾

startswith(prefix[, start[ end]]) -> bool

在指定的区间[start, end) ,字符串是否是prefix开头

S = "I am very very very sorry"

s.startswith('very')

s.startswith('very', 5)

s.startswith('very', 5, 9)

s.endswith('very', 5, 9)

s.endswith('sorry', 5)

s.endswith('sorry',5, -1)

s.endswith('sorry', 5, 100)

 

十一、字符串判断is系列


isalnum() -> bool是否是字母和数字组成

isalpha() 是否是字母

isdecimal()是否只包含十进制数字

isdigit()是否全部数字(0~9)

isidentifier() 是不是字母和下划线开头,其他都是字母、数字、下划线

islower()是否都是小写

isupper()是否全部大写

isspace()是否只包含空白字符

 

十二、字符串格式化


字符串的格式化是一种拼接字符串输出样式的手段,更灵活方便

join拼接只能使用分隔符,且要求被拼接的是可迭代对象

+拼接字符串还算方便,但是非字符串需要先转换为字符串才能

在2.5版本之前,只能使用printf style风格的print输出

printf-style formatting,来自于C语言的printf函数

格式要求:

占位符:使用%和格式字符组成,例如%s、%d等

s调用str(),r会调用repr()。所有对象都可以被这两个转换。

占位符中还可以插入修饰字符,例如%03d表示打印3个位置,不够前面补零format % values,格式字符串和被格式的值之间使用%分隔

values只能是一个对象,或是一个和格式字符串占位符数目相等的元组,或一个字典

printf-style formatting举例

"I am %03d"%(20,)

'l like %s.' % 'Python'

'%3.2f%%,0x%x, 0X%02X' % (89.7654,10,15)

"I am %-5d" %(20,)

C语言的printf

4.7.2. printf-style String Formatting

Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str. format () interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.

String objects have one unique built-in operation. the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % corversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language.

If format requires a single argument, valuos may be a single non-tuple object [5] Othewise, values must be a tuple with exactly the number of items specifed by the format string, or a single mapping object (for example, a dictionary).

A conversion specifer contains two or more characters and has the fllowing components, which must occur in this order.

1. The'x' character, which marks the start of the specifer.

2.Mapping key (optional), consisting of a parenthesised sequelce of characters (for example, (somename)).

3. Conversion flags (optional), which affect the result of some conversion types.

4. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to corvert comes after the minimum field width and optional precision.

5. Precision (optional), given as a'.' (dolfollowed by the precision. If specified as ' *' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to corvert comes after the precision.

6. Length modifer (optional).

7. Corversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the sting must include a parenthesised mapping key into that dictionary inserted immediately after the'%' character. The mapping key selects the value to be formatted from the mapping.

The grammar for a replacement field is as follows:

"First,thou shalt count to {0}"

# References first positional argument

"Bring me a {}"

# Implicitly references the first positional argument

"From {} to {}”

# Same as "From {0} to {1}”

"My quest is {name}

# References keyword argument' name

"Weight in tons {0. weight}”

# 'weight’attribute of first positional arg

"Units destroyed: {playeIs[0]}"

# First element of keyword argument 'players .


Format函数格式字符串语法——python鼓励使用

"( {xxx)" .format(*args, **kwargs) -> str

args是位置参数,是一个元组

kwargs是关键字参数,是一个字典

花括号表示占位符

{}表示按照顺序匹配位置参数,{n}表示取位置参数索引为n的值

{xxx}表示在关键字参数中搜索名称一致的

{{}}表示打印花括号

45=4*10**1+5*10**0

2a=2*16**1+10

 

字符串格式化

位置参数

"{}:{}".format(192.168.1.100%,8888),这就是按照位置顺序用位置参数替换前面的格式字符串的占位符中

关键字参数或命名参数

"[server} {(1]}:{0} ".format(8888, 192.168.1.100', server='Web Server Info:'),位置参数按照序号匹配,

关键字参数按照名词匹配

访问元素

"{0[0]}.{0[1]}".format(("magedu'; 'com'))

对象属性访问

from collections import namedtuple

Point = namedtuple('Point", 'x y')

p = Point(4,5)

"{{{0.x},{0.y}}}".format(p)

 

对齐

'{0}*{1}={2:<2y .format(3,2,2*3)

'{0}*{1}={2:<02) .format(3,2,2*3)

'{0}*{1}={2:>02]'.format(3,2,2*3)

'{:^:30}" .format('centered')

'{:*^:*入 30}'.format('centered')


进制

"int: {0:d; hex: {0:x}; oct: {0:o}; bin:{0:b]".format(42)

"int: {0:d}; hex: {0:#x}; oct:{O:#o}; bin:{0:#b}".format(42)

octets = [192,168,0,1]

"(:02X}:02X}:02X}:02X)'.format(*octets)

 

浮点数

print("".format(3**0.5))#1.7320508075688772

print("{f:g}".format(3**0.5))#1.73205

print(" :f) ".format(3**0.5))#1.72205营

print(" :10fy".format(3 **0.5))#右对齐

print(":2}".format(102.231))#宽度为2

print("E:.2]”.format(3**0.5))#1.7 2个数字

print("E:.2f)".format(3**0.5))#1.73 小数点后2位

print(" :3.2f}".format(3**0.5))# 1.73 宽度为3,小数点后2位

print("{:3.3f}".format(0.2745))#0.275

print(":3.3%}".format(1/3))# 33.333%

字符串格式化***

请使用format函数格式化字符串

 

十三、字符串练习


用户输入一个数字

判断是几位数

打印每一位数字及其重复的次数

依次打印每一位数空顺序个,十,百,千,万等

输入5个数字,打印每个数字的位数,将这些数字排序打印,要求升序打印

相关文章
|
14天前
|
存储 算法 数据库
使用python hashlib模块给明文字符串加密,以及如何撞库破解密码
`hashlib` 是 Python 中用于实现哈希功能的模块,它可以将任意长度的输入通过哈希算法转换为固定长度的输出,即散列值。该模块主要用于字符串加密,例如将用户名和密码转换为不可逆的散列值存储,从而提高安全性。`hashlib` 提供了多种哈希算法,如 `md5`、`sha1`、`sha256` 等。
32 1
|
22天前
|
存储 索引 Python
四:《Python基础语法汇总》— 字符串操作
本篇文章详细讲述了关于如何获取字符串中元素的操作(为了方便大家理解,着重讲述了下标索引与切片),及字符串的常用方法与函数和字符串的运算
15 2
四:《Python基础语法汇总》— 字符串操作
|
29天前
|
存储 索引 Python
Python学习笔记----列表、元组和字典的基础操作
这篇文章是一份Python学习笔记,涵盖了列表、元组和字典的基础操作,包括它们的创建、修改、删除、内置函数和方法等。
Python学习笔记----列表、元组和字典的基础操作
|
14天前
|
Python
python字符串常用操作方法
python字符串常用操作方法
|
15天前
|
数据采集 Python
|
19天前
|
程序员 测试技术 开发工具
豆瓣评分7.9!世界级讲师耗时5年整理出的Python学习手册!
Python是一门流行的开源编程语言,广泛用于各个领域的独立程序与脚本化应用中。它不仅免费、可移植、功能强大,同时相对简单,而且使用起来充满乐趣。从软件业界的任意一角到来的程序员,都会发现Python着眼于开发者的生产效率以及软件质量,因此无论你的项目是大还是小,选择Python都将带来战略性的优势。 今天给小伙伴们分享的这份手册讲述了完整的Python语言,力争满足“语言”和“原理”两个方面的需求,并拥有足够的深度以便实用。废话不多说,下面展示给大家。
|
20天前
|
数据采集 数据可视化 Ruby
GitHub星标破万!Python学习教程(超详细),真的太强了!
Python 是一门初学者友好的编程语言,想要完全掌握它,你不必花上太多的时间和精力。 Python 的设计哲学之一就是简单易学,体现在两个方面: 1. 语法简洁明了:相对 Ruby 和 Perl,它的语法特性不多不少,大多数都很简单直接,不玩儿玄学。 2. 切入点很多:Python 可以让你可以做很多事情,科学计算和数据分析、爬虫、Web 网站、游戏、命令行实用工具等等等等,总有一个是你感兴趣并且愿意投入时间的。
|
26天前
|
SQL JSON C语言
Python中字符串的三种定义方法
Python中字符串的三种定义方法
|
29天前
|
Python
Python学习笔记---函数
这篇文章是一份Python函数学习的笔记,涵盖了使用函数的优势、内置函数的调用、自定义函数的定义、函数参数的不同类型(必须参数、关键字参数、默认参数、可变参数)、有返回值和无返回值的函数、形参和实参、变量作用域、返回函数、递归函数、匿名函数、偏函数以及输入和输出函数等多个函数相关的主题。
|
29天前
|
索引 Python
Python学习笔记----操作字符串
这篇文章是一份Python字符串操作的学习笔记,涵盖了字符串相加、序列相加、字符串长度和字符的查找、统计、分割、连接、替换、去除空白、大小写转换以及判断字符串是否由字母和数字组成等常用方法。
Python学习笔记----操作字符串