python RE模块 替换字符串和分割字符串

1:替换字符串sub()函数

语法:re.sub(pattern,repl,string,count,flags)
参数说明:

  • pattern 表示模式字符串
  • repl 表示替换的字符串
  • string 不爱护要被查找替换的原始字符串
  • count 可选参数表示模式匹配后的替换最大次数,默认值为0,表示替换所有的匹配
  • flags 可选参数,表示标识位,用于控制匹配方式,如是否需要区分字母的大小
    代码示例:
pattern = r'1[345678]\d{9}'  # 模式字符串
str1 = '中奖号码为:84978941 联系电话为13838384383'

result = re.sub(pattern,'13666666666',str1)
print result
# 中奖号码为:84978941 联系电话为13666666666

2:分割字符串spilt()

re模块的spilt()和字符串的spilt()的类似,所不同的是所分割的字符串是由模式字符串指定。
语法:re.spilt(pattern,string,[maxsplit],[flags])
参数说明:

  • pattern 表示模式字符串,要由匹配的正则表达式转换而来。
  • string 表示要匹配的字符串
  • maxsplit 可选参数,表示最大的拆分次数
  • flags 可选参数,表示标志位,用于控制匹配方式,如是否区分字母的大小写。

代码示例:

pattern = r'[?|&]'  # 模式字符串
url = 'http://www.mingrisoft.com/login.jsp?username="mr"&pwd="mingrisoft"'
result = re.split(pattern,url)
print result
# ['http://www.mingrisoft.com/login.jsp', 'username="mr"', 'pwd="mingrisoft"']

我是阿旺,周末出去两天玩了,去张家口,没有更新
所谓成熟,就是越来越发觉以前的自己是个傻逼。
我突然想到了一个药品的名称,“曲马多”曾经高中时以为嗑药很酷,但是想想那个时候真傻逼。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,可以使用多种方法来分割字符串并去除标点符号。其中一种常见的方法是使用正则表达式。可以使用re模块的sub()函数来替换字符串中的标点符号。首先,需要定义一组标点符号,然后使用re.sub()函数将字符串中的标点符号替换为空字符串。具体的代码如下所示: ```python import re import string def remove_punctuation(text): punctuation = string.punctuation pattern = r"\[{}\]".format(punctuation) text = re.sub(pattern, "", text) return text text = "Hello, World!" text_without_punctuation = remove_punctuation(text) print(text_without_punctuation) ``` 输出结果为:"Hello World"。在这个例子中,我们首先导入了re模块和string模块。然后,定义了一组标点符号,即string.punctuation。接下来,使用re.sub()函数将字符串中的标点符号替换为空字符串。最后,将处理后的字符串打印出来。 除了使用正则表达式,还可以使用字符串的replace()方法来删除标点符号。具体的代码如下所示: ```python import string def remove_punctuation(text): punctuation = string.punctuation for char in punctuation: text = text.replace(char, "") return text text = "Hello, World!" text_without_punctuation = remove_punctuation(text) print(text_without_punctuation) ``` 输出结果为:"Hello World"。在这个例子中,我们使用了字符串的replace()方法来逐个替换字符串中的标点符号。首先,定义了一组标点符号,即string.punctuation。然后,使用for循环遍历标点符号,并使用replace()方法将每个标点符号替换为空字符串。最后,将处理后的字符串打印出来。 #### 引用[.reference_title] - *1* *2* *3* [chatgpt赋能pythonPython中如何删除字符串中的标点符号](https://blog.csdn.net/www_xuhss_com/article/details/131149195)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值