简体   繁体   中英

how can I compare “hello:”==“hello” in python

我想忽略字符串中的符号,并与非符号字符串name="Avengers Endgame"

find_element_by_link_text(name.title()).click()
<a href="#">Avengers: Endgame</a>

You could use a regex on the word class ( \\W ). From the link,

 \\W Matches any character which is not a word character. This is the opposite of \\w. If the ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_]. If the LOCALE flag is used, matches characters considered alphanumeric in the current locale and the underscore. 

Like,

import re
a = 'Avengers Endgame'
b = 'Avengers: Endgame'
if re.sub(r'[\W]', '', a) == re.sub(r'[\W]', '', b):
    print("They match")

I wrote this function for another project. Use re module, I guess it can help you.

def convert_string(str):
    '''
    return the string without any signs

    ex :
    input = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
    ouput = 'abcdefghijklmnopqrstuvwxyz123456789'
    '''

    pat = re.compile(r'[^a-zA-Z0-9]', flags=re.IGNORECASE)
    return pat.sub('', str)

you could use a generator expression to only yield characters from your string that are alphanumeric or whitespace, then join them back into a new string:

text = 'Avengers: Endgame'
stripped_text = ''.join(char for char in text if char.isalnum() or char.isspace())

your new string would then be: Avengers Endgame

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