简体   繁体   中英

Removing special symbols in from python string

I am trying to remove all kinds of special symbols from each word in the given string sen but I'm not able to figure a method in python to properly achieve it.

import string
def LongestWord(sen): 

    maxlen = 0
    count = 0
    words = sen.split()
    for word in words:
        ''.join(e for e in word if e.isalnum())
        if maxlen < len(word):
            maxlen = len(word)
            sen = words[count]
        count = count +1
    return sen

    # keep this function call here  
    print LongestWord(raw_input())

For the following string : "a beautiful sentence^&!"

I get this as the output : sentence^&!

Please help in figuring out how to remove this special symbols and punctuation marks.

Have a look at Python String join() Method .

This method returns a string, which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method.

In short, you need to save what it returns in a variable.

def LongestWord(sen):
    words = sen.split()
    answer_string = ''
    for word in words:
        answer_string += ''.join(e for e in word if e.isalnum())
    return answer_string

print(LongestWord("a beautiful sentence^&!"))

Output:

abeautifulsentence

只需要将''.join(...)结果存储在一个变量中

word = ''.join(e for e in word if e.isalnum())

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