當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python String rstrip()用法及代碼示例

rstrip()方法返回字符串的副本,其中刪除了尾隨字符(基於傳遞的字符串參數)。如果未傳遞任何參數,它將刪除尾隨空格。

用法:

string.rstrip([chars])

參數:


  • chars (optional) – a string specifying the set of characters to be removed.

返回值:

returns a copy of the string with trailing characters stripped

代碼1:

# Python3 program to demonstrate the use of  
# rstrip() method using optional parameters  
  
# string which is to be stripped 
string = "geekssss"
  
# Removes given set of characters from 
# right. 
print(string.rstrip('s')) 
輸出:
geek

代碼2:

# Python3 program to demonstrate the use of  
# rstrip() method using optional parameters  
  
# string which is to be stripped 
string = "   for    "
  
# Leading whitespaces are removed 
print("Geeks" + string.rstrip() + " Geeks "
輸出:
Geeks   for Geeks

代碼3:

# string which is to be stripped 
string = "geeks for geeks"
  
# Argument doesn't contain trailing 's' 
# So, no characters are removed 
print(string.rstrip('ek')) 
輸出:
geeks for geeks

代碼4:

# string which is to be stripped 
string = "geeks for geeks"
  
# Removes given set of characters from 
# right. 
print(string.rstrip('ske')) 
輸出:
geeks for g


相關用法


注:本文由純淨天空篩選整理自Akanksha_Rai大神的英文原創作品 Python | String rstrip()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。