[英]How to remove a character from a string within a list PYTHON
我目前有以下代碼,但我正在努力找出將從列表中的字符串中刪除標點符號的代碼。 如果您知道我應該輸入什么,請告訴我。
"""
This function checks to see if the last character is either punctuation or a
"\n" character and removes these unwanted characters.
Question: 1
"""
import string
result = string.punctuation
def myFun(listA):
A = listA
for element in A:
for i in element:
if i in result:
#what do i put here
print(A)
myFun(['str&', 'cat', 'dog\n', 'myStr.'])
在 Python 中, string 基本上是一個字符列表,因此您可以通過str[-1]
訪問最后一個字符,或者如果您想檢查\\n
,則str[-2:]
現在,您可以首先對str[-1]
執行簡單的檢查,
if str[-1] in string.punctuation
並用str = str[:-1]
刪除它
和str[-2:]
由:
if str[-2:] == "\\n"
並用str = str[:-2]
刪除它
注意:每次執行完檢查后,記得加一個continue
來迭代到下一個循環,否則會從str
刪除兩次同時以\\n
和標點符號結尾的情況,例如“test\\n”,將成為“測試”
ps 我故意沒有把它們放在你的代碼中,而是把那部分留給你去做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.