Python面试一百题——字符串与正则表达式

目录

  1. 字符串格式化之模板字符串
  2. 使用fstring方式格式化字符串
  3. 字符串的基本操作
  4. 向字符串的format方法传递参数有几种方式
  5. 让字符串居中显示
  6. 连接列表中的元素值
  7. 用正则表达式判断字符串中是否包含日期
  8. 寻找字符串中的手机号
  9. 用正则表达式分别提取电话号的区号、电话号和分机号
  10. 用正则表达式查找字符串中所有的Email
  11. 用正则表达式格式化字符串中所有的浮点数
  12. 提取HTML页面中的URL

01.字符串格式化之模板字符串

在这里插入图片描述
格式化字符串的方式:

  1. %格式化
  2. 模板字符串
  3. format方法
  4. fstring
# 模板字符串
# 通过Template对象封装,用 $ 放置一些占位符,并通过substitute方法用实际的值替换这些占位符
from string import Template

template1 = Template('$s真棒,$s真厉害')  # '$s真棒,$s真厉害' 就是模板字符串
print(template1.substitute(s = '我'))	# 我真棒,我真厉害
print(template1.substitute(s = '你'))	# 你真棒,你真厉害

template2 = Template('${h}ello world')	# 用{}将占位符名称括起来,以便和其他单词区分
print(template2.substitute(h = 'abc'))

template3 = Template('$dollar$$相当于$pound£')	# 若要输出$符号,则用$$
data = {}
data['dollar'] = 20
data['pound'] = 15.3
print(template3.substitute(data))	# 数据可放到字典中,更方便

总结
在这里插入图片描述

02.使用fstring方式格式化字符串

在这里插入图片描述

# fstring
name = 'Bill'
age = 20
def toAge():
    return age + 1

s = f'我是{name},今年{age}岁,明年我{toAge()}岁'    #前面加上 f 表明有变量或函数
print(s)
我是Bill,今年20岁,明年我21class Person:
    def __init__(self):
        self.name = 'Mike'
        self.age = 40
    def getAge(self):
        return self.age + 1

person = Person()
s1 = f'我是{person.name},今年{person.age}岁,明年我{person.getAge()}岁'   #对象内的成员也可以
print(s1)
我是Mike,今年40岁,明年我41

总结
在这里插入图片描述

03.字符串的基本操作

在这里插入图片描述

# 1:通过索引获取字符串中的某个字符(串)
s1 = 'hello world'
print(s1[1])

# 分片
print(s1[6:9])
print(s1[::2])

# 乘法,重复输出
print(s1 * 2)

# 字符是否在字符串中
print('b' in s1)
print('b' not in s1)

# 获取字符串长度、最大最小值
print(len(s1))
print(max(s1))
print(min(s1))

# 列表同样有用
# 但字符串不可以通过索引修改

04.向字符串的format方法传递参数有几种方式

在这里插入图片描述

# 默认方式(传入的参数与{}一一对应)、命名参数和位置参数

# 第二题
s1 = 'Today is {},the temperature is {} degree.'
print(s1.format('Sat', 20))
Today is Sat,the temperature is 20 degree.

s2 = 'Today is {day},the temperature is {degree} degree.'
print(s2.format(degree= 20, day= 'Sun'))
Today is Sun,the temperature is 20 degree.

s3 = 'Today is {day},{},the {} temperature is {degree} degree.'
print(s3.format('abcd', 1234, degree= 24, day= 'Sun'))
Today is Sun,abcd,the 1234 temperature is 24 degree.

s4 = 'Today is {day},{1},the {0} temperature is {degree} degree.'
print(s4.format('abcd', 1234, degree= 24, day= 'Sun'))
Today is Sun,1234,the abcd temperature is 24 degree.

class Person:
    def __init__(self):
        self.age = 20
        self.name = 'Bill'
person = Person()

s5 = 'My name is {p.name},my age is {p.age}.'
print(s5.format(p = person))
My name is Bill,my age is 20.

总结
在这里插入图片描述

05.让字符串居中显示

在这里插入图片描述

# 1:center方法、format方法

# 2:
print('<' + 'hello'.center(30) + '>')
print('<' + 'hello'.center(30, '#') + '>')
<############hello#############>

print('<{:^30}>'.format('hello'))
print('<{:#^30}>'.format('hello'))
<############hello#############>

总结
在这里插入图片描述

06.连接列表中的元素值

在这里插入图片描述

a = ['a', 'b', 'c', 'd', 'd']
s = '+'
print(s.join(a))	#用s分割a
a+b+c+d+d

# 作用:连接路径
dirs = 'D:', 'A', 'code', 'python', 'test'
print(dirs)	# 元组 ('D:', 'A', 'code', 'python', 'test')
path = '\\'.join(dirs)
print(path)	# D:\A\code\python\test

# 注意:连接的元素必须是字符串类型
n = [1, 2, 3, 4]
s = '+'
print(s.join(n))
Traceback (most recent call last):
  File "D:/A/test.py", line 3, in <module>
    print(s.join(n))
TypeError: sequence item 0: expected str instance, int found

总结
在这里插入图片描述

07.用正则表达式判断字符串中是否包含日期

在这里插入图片描述

import re # 专门处理正则表达式

print(re.match('hello', 'hello'))
<_sre.SRE_Match object; span=(0, 5), match='hello'>

print(re.match('hello', 'ahello'))
None # 不匹配返回None

print(re.match('.hello', 'ahello'))	# . 表示任意字符
<_sre.SRE_Match object; span=(0, 6), match='ahello'>

print(re.match('.*hello', 'aahello'))	# * 表示任意数量
<_sre.SRE_Match object; span=(0, 7), match='aahello'>

# 第二题
s = 'Today is 2020-02-06.'
m = re.match('.*\d{4}-\d{2}-\d{2}.*', s)	# \d表示数字 {4}表示四位

if m is not None:
    print(m.group())
Today is 2020-02-06.

08.寻找字符串中的手机号

在这里插入图片描述
区别:match用于匹配,search用于搜索

import re

print(re.match('.*python', 'i love python'))
<_sre.SRE_Match object; span=(0, 13), match='i love python'>
print(re.search('python', 'i love python'))
<_sre.SRE_Match object; span=(7, 13), match='python'>

# 搜索手机号
n = re.search('1\d{10}', 'phone number:12345487899')	# 限制第一位为 1 
if n is not None:
    print(n.group())
    print(n.start())
    print(n.end())
12345487899
13
24

总结
在这里插入图片描述

09.用正则表达式分别提取电话号的区号、电话号和分机号

在这里插入图片描述

# 正则表达式分组
import re

n = re.search('(\d{3})-(\d{7,})-(\d{3,})', 'phone number:024-123456789-5446')
#至少7位用 {7,},分组用()括起来并且用 n.groups
if n is not None:
    print(n.group())	# 024-123456789-5446
    print(n.groups())	# ('024', '123456789', '5446')
    print(n.groups()[0])	# 024	
    print(n.groups()[1])	# 123456789
    print(n.groups()[2])	# 5446

总结
在这里插入图片描述

10.用正则表达式查找字符串中所有的Email

在这里插入图片描述

import re

n = '我的email地址是abCde@163.com,你的地址是多少?是xYz@163.net吗?还是dkgsdf@gmail.org?'
prefix = '[0-9a-z]+@[0-9a-zA-Z]+\.'
result = re.findall(prefix + 'com|' + prefix + 'net', n, re.I) # I 忽略大小写
# 'com|' 或后面要加完整的正则表达式 不能直接加'net',要不然就把'net'当条件
print(result)
['abCde@163.com', 'xYz@163.net']

总结
在这里插入图片描述

11.用正则表达式格式化字符串中所有的浮点数

在这里插入图片描述

import re
'''
1.如何用正则表达式表示浮点数 考虑负数: -?\d+(\.\d+)? (-?表示可能有或没有负数,(\.\d+)?表示可能有或没有小数)
2.格式化浮点数 format
3.如何替换原来的浮点数 sub:只返回替换的结果 subn:返回元组(替换的结果, 替换的次数)
'''
result = re.subn('-?\d+(\.\d+)?', '##', 'Pi is 3.14159265, e is 2.71828183, -0.1 + 1.3 = 1.1')
print(result)	# ('Pi is ##, e is ##, ## + ## = ##', 5)
print(result[0])	# Pi is ##, e is ##, ## + ## = ##
print(result[1])	# 5

def fun(match):
    return '<' + match.group() + '>'

result = re.subn('-?\d+(\.\d+)?', fun, 'Pi is 3.14159265, e is 2.71828183, -0.1 + 1.3 = 1.1')
print(result)	#('Pi is <3.14159265>, e is <2.71828183>, <-0.1> + <1.3> = <1.1>', 5)

def fun(match):
    return format(float(match.group()), '0.2f')

result = re.subn('-?\d+(\.\d+)?', fun, 'Pi is 3.14159265, e is 2.71828183, -0.1 + 1.3 = 1.1')
print(result)
# ('Pi is 3.14, e is 2.72, -0.10 + 1.30 = 1.10', 5)

总结
在这里插入图片描述

12.提取HTML页面中的URL

在这里插入图片描述

import re

s = '<a href="www.baidu.com">百度</a> <a href="www.google.com">谷歌</a>'
result = re.findall('<a[^<]*href="([^<]*)">', s, re.I) #a和href中可能有除了<外的其他东西 [^<}
print(result)
['www.baidu.com', 'www.google.com']
for url in result:
    print(url)
www.baidu.com
www.google.com

总结
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值