简体   繁体   English

从python字符串中删除特殊符号

[英]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.我试图从给定字符串sen中的每个单词中删除各种特殊符号,但我无法在 python 中找到一种方法来正确实现它。

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^&!我得到这个作为输出:sentence^&!

Please help in figuring out how to remove this special symbols and punctuation marks.请帮助弄清楚如何删除这些特殊符号和标点符号。

Have a look at Python String join() Method .看看Python String join() 方法

This method returns a string, which is the concatenation of the strings in the sequence seq.此方法返回一个字符串,它是序列 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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