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地址是[email protected],你的地址是多少?是[email protected]嗎?還是[email protected]?'
prefix = '[0-9a-z]+@[0-9a-zA-Z]+\.'
result = re.findall(prefix + 'com|' + prefix + 'net', n, re.I) # I 忽略大小寫
# 'com|' 或後面要加完整的正則表達式 不能直接加'net',要不然就把'net'當條件
print(result)
['[email protected]', '[email protected]']

總結
在這裏插入圖片描述

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

總結
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章