J'essaie d'inverser une chaîne sans affecter des caractères spéciaux, mais cela ne fonctionne pas. Voici mon code:
def reverse_each_word(str_smpl): str_smpl = "String; 2be reversed..." #Input that want to reversed lst = [] for word in str_smpl.split(' '): letters = [c for c in word if c.isalpha()] for c in word: if c.isalpha():`enter code here` lst.append(letters.pop()) continue else: lst.append(c) lst.append(' ') print("".join(lst)) return str_smpl def main(): #This is called for assertion of output str_smpl = "String; 2be reversed..." #Samplr input assert reverse_each_word(str_smpl) == "gnirtS; eb2 desrever..." #output should be like this return 0
4 Réponses :
Essayez le code suivant:
from string import punctuation sp = set(punctuation) str_smpl = "String; 2be reversed..." #Input that want to reversed lst = [] for word in str_smpl.split(' '): letters = [c for c in word if c not in sp] for c in word: if c not in sp: lst.append(letters.pop()) continue else: lst.append(c) lst.append(' ') print("".join(lst))
ou essayez-le avec itheroTools.groupby code>,
Voulez-vous dire comme ça ?:
def reverse_string(st): rev_word='' reverse_str='' for l in st: if l.isalpha(): rev_word=l+rev_word else: reverse_str+=rev_word rev_word='' reverse_str+=l return reverse_str def main(): string=' Hello, are you fine....' print(reverse_string(string)) if __name__=='__main__': main()
également nécessaire pour affirmer cela par la méthode principale ()
def reverse_string_without_affecting_number(text): temp = [] text = list(text) for i in text: if not i.isnumeric(): temp.append(i) reverse_temp = temp [::-1] count = 0 for i in range(0,len(text)): if not text[i].isnumeric(): text[i] = reverse_temp[count] count +=1 else: continue return "".join(text) print (reverse_string_without_affecting_number('abc1235de9f15ui'))