程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python removes the specified characters in the string [easy to understand]

編輯:Python

Hello everyone , I meet you again , I'm your friend, Quan Jun .

python Medium strip() You can remove the specified characters at the beginning and end

ss = ' My phone number is 18827038663, It's also a micro signal ,\n Please join , thank you \n\n\n'
print(ss.strip('\n'))

result :

 My phone number is 18827038663, It's also a micro signal ,
Please join , thank you 

You can see that only the specified characters at the beginning and end can be deleted .

Want to remove the middle character , have access to replace() function

ss = ' My phone number is 18827038663, It's also a micro signal ,\n Please join , thank you \n\n\n'
print(ss.replace('\n', ''))

result :

 My phone number is 18827038663, It's also a micro signal , Please join , thank you 

note:

1. strip(str)

Basic usage :ss.strip(rmStr)

ss.strip() When the parameter is empty , Default removal ss The beginning and end of the string \r, \t, \n, Spaces and other characters ; When the parameter is a certain character , You can remove the specified characters at the beginning and end , for example :

Input :

ss = ' My phone number is 18827038663, It's also a micro signal , Please join , Thank you, Lala '
print(ss.strip(' Yeah '))

Running results :

 My phone number is 18827038663, It's also a micro signal , Please join , thank you 

We need to pay attention to strip Is in accordance with the Character level Matching , As long as the head and tail appear Characters in the character set , Will be strip fall , Instead of matching the whole character .

ss.lstrip() Delete ss The specified character at the beginning of the string ,ss.rstrip() Delete ss The specified character at the end

2. replace(old, new[, max])

Basic usage :ss.replace(old, new[, max])

old Is the character in the original string ,new Is a new string that needs to be replaced with ,max Is the maximum number of matches , Match from left to right at most max Time . In general, it is not set max Value , Replace all by default .

Input :

ss = 'old old string'
ret = ss.replace('old', 'new', 1)
print(ret)

Output :

new old string

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/130948.html Link to the original text :https://javaforall.cn


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved