从字符串中删除非字母数字字符,并将字符串和单词拆分为列表,以查看使用正则表达式是否满足条件

2024-10-02 14:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Issue

我正在完成一个接受sys参数(字符串)并检查它是否是回文的程序。如果我只有一个单词字符串,我当前的代码就可以工作。但是,我需要确保程序将检查每个单词,而不是任何非字母数字字符的因素。如果其中任何一个单词是回文,那么它会一次性打印它是回文

思维过程:

我的想法是将每个单词分成一个列表,让列表迭代以查看是否满足条件,然后只打印一次。如果我有多个单词,它会打印出来,而不是回文。目前,如果我提供一个包含多个单词的字符串,它只会多次打印它不是回文:即“racecar,racecar”

如有任何建议,将不胜感激

这是到目前为止我的代码


def palindrome():

    string = sys.argv[1].lower()
    remove_punc = string.strip('~`!@$%^&*()_-+={}[]|\:;<,>.?/')
    converted_string = remove_punc.split(' ')


    for i in converted_string:
        if converted_string == converted_string[::-1]:
            print('It\'s a palindrome!')
            break

        else:
            print('It\'s not a palindrome!')

palindrome()

Tags: 字符串代码程序列表参数stringsysit
3条回答

当您输入超过1个单词(前面或后面有空格的东西)时, 如果您想获得每个单词,则需要获取除程序本身之外的所有参数。然后从非alpha字符中清除它们,然后可以测试它们

import sys


def palindromes():

    words = sys.argv[1:]
    cleaned_words = [
        w.strip('~`!@$%^&*()_-+={}[]|\:;<,>.?/')
        for w in words
    ]
    for word in cleaned_words:
        if word == word[::-1]:
            print(f'{word} is a palindrome!')
        else:
            print(f'{word} is not a palindrome!')


palindromes()

测试:

$ python palindromes.py foo aba bar boob
foo is not a palindrome!
aba is a palindrome!
bar is not a palindrome!
boob is a palindrome!

我很感激这些意见书,这是我工作的主要部分

    new_string = ''.join(i if i.isalpha() else '' for i in string)
    if new_string == new_string[::-1]:
        print('It\'s a palindrome!')
    else:
         print('It\'s not a palindrome!')

你是说这个吗

import re

s = "aaa bbb, aaa"

s = re.sub("[^A-z]", "", s)

print(s == s[::-1])

Update

没有正则表达式:

s = "Al lets Della call Ed “Stella.”"

s = "".join([x for x in s.lower() if 123>ord(x)>96])

print(s == s[::-1])

要使用args,请执行以下操作:

s = sys.argv[1]

s = "".join([x for x in s.lower() if 123>ord(x)>96])

print(s == s[::-1])

enter image description here

Update 2

如果要同时检查多个回文,请执行以下操作:

import sys

for s in sys.argv[1:]:
    x = "".join([x for x in s.lower() if 123>ord(x)>96])
    print("'"+ s + "' is a palindrome? ", x == x[::-1])

enter image description here

相关问题 更多 >