【Python学习笔记】三、字符串

1.字符串的基本操作

同序列一样有索引、分片、乘法、in运算符、len、min、max等操作。

2.格式化字符串

formatStr="Hello %s.Today is %s,How are you?" #定义字符串模板
val1=('Mike','Wednesday') #初始化字符串格式化参数值,此处必须使用元组,不能用列表
print(formatStr % val1) #格式化字符串
> Output:Hello Mike.Today is Wednesday,How are you?

Str="这件事的成功率是%d%%,如果有%s的参与,成功率会提升至%.4f%%"
val2=(50,'John',99.99)
print(Str % val2)
> Output:这件事的成功率是50%,如果有John的参与,成功率会提升至99.9900%

3.模板字符串

在string模块中提供了一个用于格式化字符串的Template类,该类的功能是用同一个值替换所有相同的格式化参数。格式化时需使用Template类的substitute方法,该方法用于指定格式化参数对应的值。

from string import Template

tem1=Template("$s 啊啊啊 $s 哦哦哦")
print(tem1.substitute(s='Hello')) # Hello 啊啊啊 Hello 哦哦哦

tem2=Template("${s}efg")
print(tem2.substitute(s="abcd")) # abcdefg

tem3=Template("$dollar$$相当于多少$pounds")
print(tem3.substitute(dollar=20,pounds='英镑')) #20$相当于多少英镑

tem4=Template("$dollar$$相当于多少$pounds")
data={}
data['dollar']=100
data['pounds']='英镑'
print(tem4.substitute(data)) # 100$相当于多少英镑

4.字符串的format方法

#按顺序指定格式化参数值
s1="Today is {},the temperature is {} degrees."
print(s1.format("Saturday",24))
> Output:Today is Saturday,the temperature is 24 degrees.

#按关键字格式化参数值
s2="Today is {week},the temperature is {degree} degrees."
print(s2.format(week="Sunday",degree=20))
> Output::Today is Sunday,the temperature is 20 degrees.

#上述两种混合
s3="Today is {week},{},the {} temperature is {degree} degrees."
print(s3.format("aaaa",12345,week="Sunday",degree=20))#前面是按顺序传递的格式化参数值,后面是按关键字格式化参数值,顺序不能调换
> Output:Today is Sunday,aaaa,the 12345 temperature is 20 degrees.

s4="Today is {week},{1},the {0} temperature is {degree} degrees."# {1}表示从format方法的第1个参数取值(从0开始计数)
print(s4.format("aaaa",12345,week="Sunday",degree=20))
> Output:Today is Sunday,12345,the aaaa temperature is 20 degrees.
#定义一个列表,获取列表中的值
fullname=["Bill","Mike"]
print("Mr {name[1]}".format(name=fullname))
> Output:Mr Mike

#访问math模块中的“__name__”变量来获取模块的名字,访问math模块中的pi变量获取PI的值
import math
s="The {mod.__name__} module defines the value {mod.pi} for PI"
print(s.format(mod=math))
> Output:The math module defines the value 3.141592653589793 for PI
更进一步控制字符串格式化参数

在使用下述的字符串格式化类型时要在前面加:或!,大多数加:,有一部分(如a、r)要加!

print("result是{:f}".format(5)) #Output: result是5.000000
print("result是{:.2f}".format(5)) #Output: result是5.00

print("十进制:{num:c} 二进制:{num:b} 八进制:{num:o} 十六进制:{num:x}".format(num=25))
# Output: 十进制:25 二进制:11001 八进制:31 十六进制:19

print("百分比:{num:%} 浮点数:{num:f} 科学计数法:{num:e}".format(num=0.56))
# Output: 百分比:56.000000% 浮点数:0.560000 科学计数法:5.600000e-01

print("原样输出:{qwe!s} 调用repr函数:{qwe!r} 输出Unicode编码:{qwe!a}".format(qwe="哈"))
# Output: 原样输出:哈 调用repr函数:'哈' 输出Unicode编码:'\u54c8'

5.字符串方法

①center方法

center方法用于将一个字符串在一定宽度区域居中显示,并在两侧填充指定字符。

>>>print("<"+"hello".center(30)+">") #在宽度为30的区域居中显示,两侧区域填充空格
<            hello             >

>>>print("<"+"hello".center(30,'*')+">") #同上,两侧区域改为填充*号
<************hello*************>
②find方法

find方法用于在大字符串中查找子串并返回出现位置。

s="Hello world"
print(s.find("llo"))#返回子串首字母在原字符串中的位置,运行结果为2
print(s.find("OK"))#找不到返回-1
print(s.find("o",5,9)) #可通过第二个参数指定开始查找的位置,第三个参数指定结束查找位置,运行结果为7
③join方法

join方法用于连接序列中的元素,是split方法的逆方法。
一个典型的应用就是组合出不同平台的路径,(如Linux平台和windows平台的路径)。

list=['a','b','c','d','e']
s='+'
print(s.join(list))
#Output: a+b+c+d+e

dirs='','usr','local','nginx',''
LinuxPath='/'.join(dirs)
WindowPath='C:'+'\\'.join(dirs)
print(LinuxPath) #Output: /usr/local/nginx/
print(WindowPath) #Output: C:\usr\local\nginx\

与字符串连接的序列元素必须是字符串类型,如果是其他数据类型则在调用join方法时会抛出异常。

④split方法

split方法与join方法互为逆方法。
split方法通过分隔符将一个字符串拆分成一个序列。

>>>print("1+2+3+4+5".split("+"))#将"+"作为分隔符
['1', '2', '3', '4', '5']
>>>print("1 2 3 4".split())#不指定参数则默认将所有空格作为分隔符
['1', '2', '3', '4']
⑤lower方法、upper方法和capwords函数

lower方法将字符串中所有字母转为小写,upper方法将字符串中所有字母转为大写。
capwords函数不是字符串本身的方法,而是string模块的函数,作用是将字符串中的独立的单词首字母变大写。

>>>print("hello".upper())
HELLO
>>>print("HELLO".lower())
hello
import string
s="i like python"
print(string.capwords(s))
#Output:I Like Python
⑥replace方法

replace方法用于将一个字符串的子字符串换成另一个字符串。

s="This is a car"
>>>print(s.replace("car","bike")) #返回替换后的字符串
This is a bike
>>>print(s.replace("are","bike")) #查找不到要替换的字符串则返回原字符串
This is a car
⑦strip方法

strip方法用于截掉字符串前后指定的字符。

>>>print("   abcd   ".strip()) #截掉字符串前后的空格
abcd
>>>print(" * %$ ** $ abcd*%%% $$".strip(" *%$")) #截掉字符串前后的空格、*、%、$
abcd
⑧translate方法和maketrans方法

translate方法与replace方法作用类似,都是用于替换字符串中的某一部分,区别是translate方法只用来替换单个字符,而replace方法替换的是子字符串。
效率上translate更快一些。
使用translate方法前需使用maketrans方法创建一个替换表。

s="I want to go to shanghai"
table=s.maketrans("ath","123") #创建一张替换表(a替换成1,t替换成2,h替换成3)
table1=s.maketrans("o","*"," ") #第三个参数用于指定要删除的字符(注意是字符而不是字符串)
print(table,table1)
> Output: {97: 49, 116: 50, 104: 51} {111: 42, 32: None}
print(s.translate(table)) #根据替换表替换s中相应的字符
> Output: I w1n2 2o go 2o s31ng31i
print(s.translate(table1))
> Output:Iwantt*g*t*shanghai

6.字符串的相关操作

①字符串排序

法一:利用容器(如list)的sort方法进行排序 排序

s="441651632"
l=list(s) #必须先把字符串转换为列表
l.sort() 
s=''.join(l)
print(s) #Output:112344566

法二:利用sorted函数进行排序

s="441651632"
k=''.join(sorted(s)) #调用sorted函数返回的是一个排完序的列表,故要调用join方法把列表重新转换为字符串
print(s,k) 
#Output:441651632 112344566
②字符串反转

法一:利用容器(如list)的reverse方法进行反转

s="hello world"
l=list(s) #必须先把字符串转换为列表
l.reverse()
s=''.join(l)
print(s) #Output:dlrow olleh

法二:利用reversed函数进行反转

str1="hello world"
str2=''.join(list(reversed(str1)))
print(str2) #Output:dlrow olleh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python学习笔记|字符串与正则表达式练习题答案 1. 练习题1: 题目:给定一个字符串s,找出其中的连续的最长的数字串。 答案:可以通过正则表达式来匹配数字串,然后使用max函数找出最长的。 代码示例: import re def find_longest_num_str(s): num_str_list = re.findall('\d+', s) longest_str = max(num_str_list, key=len) return longest_str s = "ab1234c56789def" print(find_longest_num_str(s)) 输出:56789 2. 练习题2: 题目:给定一个字符串s,将其中的每个空格替换为"%20"。 答案:可以通过正则表达式的sub函数来实现替换。 代码示例: import re def replace_space(s): new_s = re.sub(' ', '%20', s) return new_s s = "Hello World" print(replace_space(s)) 输出:Hello%20World 3. 练习题3: 题目:给定一个字符串s,判断它是否为回文字符串。 答案:可以使用切片操作将字符串反转,然后与原字符串进行比较。 代码示例: def is_palindrome(s): return s == s[::-1] s = "abcba" print(is_palindrome(s)) 输出:True ### 回答2: 以下是关于字符串和正则表达式练习题的答案: 1. 给定一个字符串s,编写一个函数,返回该字符串的反转字符串。 def reverse_string(s): return s[::-1] 2. 给定一个字符串s,编写一个函数,返回是否是回文字符串。 def is_palindrome(s): return s == s[::-1] 3. 给定一个字符串s和一个字符c,编写一个函数,返回字符串s中字符c的出现次数。 def count_char(s, c): return s.count(c) 4. 给定一个字符串s,编写一个函数,返回字符串s中的所有单词列表。 def split_words(s): return s.split() 5. 给定一个字符串s,编写一个函数,返回字符串s中的所有数字列表。 import re def extract_numbers(s): return re.findall(r'\d+', s) 这只是一些可能的答案,其中的解决方法可以有很多种。每个问题都有不同的解决方案,具体取决于个人的编程风格和需求。希望这些答案能够帮助你理解和学习Python中的字符串和正则表达式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值