📜  Python字符串 |条()

📅  最后修改于: 2022-05-13 01:54:34.006000             🧑  作者: Mango

Python字符串 |条()

Python的strip() 方法内置函数用于从字符串中删除所有前导和尾随空格。

使用 strip() 方法:

  • 如果左侧字符串的字符与char参数中的字符不匹配,该方法将停止删除前导字符。
  • 如果右侧字符串的字符与char参数中的字符不匹配,该方法将停止删除尾随字符。

示例 #1:

Python3
# Python code to illustrate the working of strip()
string = '   Geeks for Geeks   '
 
# Leading spaces are removed
print(string.strip())
 
# Geeks is removed
print(string.strip('   Geeks'))
 
# Not removed since the spaces do not match
print(string.strip('Geeks'))


Python3
# Python code to illustrate the working of strip()
string = '@@@@Geeks for Geeks@@@@@'
 
# Strip all '@' from beginning and ending
print(string.strip('@'))
 
string = 'www.Geeksforgeeks.org'
 
# '.grow' removes 'www' and 'org' and '.'
print(string.strip('.grow'))


Python3
# Python code to check for identifiers
def Count(string):
 
    print("Length before strip()")
    print(len(string))
 
    # Using strip() to remove white spaces
    str = string.strip()
    print("Length after removing spaces")
    return str
 
 
# Driver Code
string = "  Geeks for Geeks   "
print(len(Count(string)))


输出 :

Geeks for Geeks
for
   Geeks for Geeks   

示例 #2:

Python3

# Python code to illustrate the working of strip()
string = '@@@@Geeks for Geeks@@@@@'
 
# Strip all '@' from beginning and ending
print(string.strip('@'))
 
string = 'www.Geeksforgeeks.org'
 
# '.grow' removes 'www' and 'org' and '.'
print(string.strip('.grow'))

输出:

Geeks for Geeks
Geeksforgeeks

示例#3:
以下代码显示了 strip() 在Python中的应用。

Python3

# Python code to check for identifiers
def Count(string):
 
    print("Length before strip()")
    print(len(string))
 
    # Using strip() to remove white spaces
    str = string.strip()
    print("Length after removing spaces")
    return str
 
 
# Driver Code
string = "  Geeks for Geeks   "
print(len(Count(string)))

输出:

Length before strip()
17
Length after removing spaces
15