[英]If first or last character from string is $ remove it in python
table_name='Customer$'
if table_name.startswith('$'):
table_name=table_name[1:]
if table_name.endswith('$'):
table_name=table_name[:-1]
我嘗試了上面的代碼,它給了我正確的結果
Customer
有什么優化的方法嗎? 請回復
使用.strip()
:
table_name = '$Customer$'.strip('$')
這將從開始和結束中刪除所有$
,如果字符串周圍沒有美元,則不執行任何操作。
'$Customer$'.strip('$')
strip()
方法刪除任何前導(開頭的空格)和尾隨(結尾的空格)字符(空格是要刪除的默認前導字符)。 默認情況下,刪除尾隨和前導空格。 如果傳遞了應該刪除字符的參數,則該字符將從前導和尾隨位置中刪除
只需使用.strip()
它就像trim()
table_name = '$Cu$$stomer$'
ans = table_name.strip('$')
print(ans) # output Cu$$stomer
strip()
方法通過刪除前導字符和尾隨字符(基於傳遞的字符串參數)返回字符串的副本。
你可以從這里了解更多關於strip()
的信息: https://www.programiz.com/python-programming/methods/string/strip
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.