简体   繁体   中英

How to remove a character from a string within a list PYTHON

I currently have the following code but I am struggling to figure out the code that will remove the punctuation from the strings within the list. Please let me know if you know what I should input.

"""
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.'])

In Python, string is basically a list of characters, so you can access the last character by str[-1] , or if you wanna check for \\n , str[-2:]

Now, you can perform a simple check on str[-1] first by,

if str[-1] in string.punctuation

and remove it with str = str[:-1]

and str[-2:] by:

if str[-2:] == "\\n"

and remove it with str = str[:-2]

Notes: After you perform each checking, remember to add a continue to iterate to the next loop, or else, it will remove from the str twice for case that ends with both \\n and a punctuation, such as "test\\n," will become "test"

ps I intentionally didn't put them in your code and left that part for you to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM