thranduil Posted October 30, 2009 at 01:27 PM Report Share #294024 Posted October 30, 2009 at 01:27 PM Boas! Estou a tentar fazer um exercício que, como o nome do tópico indica, pede para fazer uma função que pega numa string de vários caracteres, analisa se algum deles é uma letra maiúscula e se for transforma-a em minúscula. O exercício diz que não podemos usar a função lower, obviamente. Eu escrevi o seguinte: def minusculas(txt): "Transforms all txt (str) upper case letters in lower case" for i in range(0, len(txt), 1) : order = ord(txt[i]) if ( order >= 65 ) and ( order <= 90 ): txt = txt[0:i] + chr(order+32) return txt Quando corro na shell comandos como minusculas('aA'), tudo corre bem e o resultado é o esperado, 'aa'. No entanto, quando corro uma letra maíscula no início da string, por exemplo, 'Aa', obtenho o seguinte erro: Traceback (most recent call last): File "<pyshell#65>", line 1, in <module> minusculas('Ab') File "C:/(...)/minusculas.py", line 23, in minusculas order = ord(txt) IndexError: string index out of range Alguém percebe o que se está a passar? Além disso, se a string for, por exemplo 'aAA', obtenho o mesmo erro! Agradecia a vossa ajuda 😉 Link to comment Share on other sites More sharing options...
newbeen Posted October 30, 2009 at 02:10 PM Report Share #294032 Posted October 30, 2009 at 02:10 PM Eu fiz umas pequenas modificações ao teu código e esta a funcionar perfeito assim def minusculas(string="IsTo e So Para TesTar Em Casa De Nada Seja PaSSaDo"): txt="" for i in string: order=ord(i) if ( order >= 65 ) and ( order <= 90 ): txt+=chr(order+32) continue txt+=chr(order) return txt RHCE - 120-062-534 Link to comment Share on other sites More sharing options...
Tharis Posted October 30, 2009 at 02:13 PM Report Share #294034 Posted October 30, 2009 at 02:13 PM O que acontece é que tu estás a percorrer a string txt e a modificá-la ao mesmo tempo. Podes fazer isso, mas não te podes esquecer de adicionar o que o resto da string (da posição onde estás até ao fim). def minusculas(txt): "Transforms all txt (str) upper case letters in lower case" for i in range(0, len(txt), 1) : order = ord(txt[i]) if ( order >= 65 ) and ( order <= 90 ): txt = txt[0:i] + chr(order+32) + txt[i+1:] return txt Outra maneira, mais fácil e melhor é criares uma nova variável. def minusculas(txt): "Transforms all txt (str) upper case letters in lower case" newtxt = "" for i in range(len(txt)) : order = ord(txt[i]) if ( order >= 65 ) and ( order <= 90 ): newtxt += chr(order+32) else: newtxt += txt[i] return newtxt print minusculas("BLAHlal") Podes também fazer one-liner! 😉 minusculas = lambda s: "".join(map(lambda c: chr(ord(c)+32) if (65 <= ord(c) and ord(c) <= 90) else c, s)) minusculas = lambda s: "".join( [ (chr(ord(c)+32) if (65 <= ord(c) and ord(c) <= 90) else c) for c in s] ) Link to comment Share on other sites More sharing options...
newbeen Posted October 30, 2009 at 02:21 PM Report Share #294035 Posted October 30, 2009 at 02:21 PM [OFF TOPIC] Esses in liners são do pior que se pode fazer pela linguagem nem com óculos se consegue ler isso [/OFF TOPIC] RHCE - 120-062-534 Link to comment Share on other sites More sharing options...
Tharis Posted October 30, 2009 at 02:38 PM Report Share #294038 Posted October 30, 2009 at 02:38 PM @newbeen, ahah... Este por acaso até é simples. Tens o lambda principal que recebe a string, tens o map que substituir UPPER por lower e tens o reduce join que pega na lista retornada pelo map e converte-a a string. 😉 Link to comment Share on other sites More sharing options...
thranduil Posted October 30, 2009 at 03:50 PM Author Report Share #294045 Posted October 30, 2009 at 03:50 PM O que acontece é que tu estás a percorrer a string txt e a modificá-la ao mesmo tempo. Podes fazer isso, mas não te podes esquecer de adicionar o que o resto da string (da posição onde estás até ao fim). xD Boa 😄 Percebo perfeitamente o erro e é dumb as hell xD Inicialmente eu pensei em construir uma outra variável mas achei que não valia a pena e que podia fazer tudo na mesma 😄 Se calhar devia ter feito o que o prof. está sempre a dizer "Primeiro façam com que o programa funcione. Preocupem-se em aperfeiçoar o código depois" 😛 Muito obrigado a todos 😉 Link to comment Share on other sites More sharing options...
hawk Posted November 7, 2009 at 01:52 PM Report Share #295035 Posted November 7, 2009 at 01:52 PM Eu tambem estou com um problema nisso. podiam dar uma olhada no meu codigo? nao sei se eleesta bem construido, mas parece me logico, e funciona, por exemplo: se escrever minusculas ("OLA"), o resultado é OLa. Ou seja, se altera a ultima letra que passou de maiuscula para minuscula. Eu pretendia converte-las todas as letras maiusculas. Obrigado pela ajuda import string def minusculas (txt): a=txt for i in a: if ord(i)>=65 and ord(i)<=90: b= string.lower (i) c=string.replace (a,i,b) print c Link to comment Share on other sites More sharing options...
thranduil Posted November 8, 2009 at 01:39 PM Author Report Share #295131 Posted November 8, 2009 at 01:39 PM hawk, se bem percebo, o que se está a passar é que sempre que chamas o string.replace, estás a pegar na string original e a substituir uma coisa. O programa num ciclo substitui o O de 'OLA'. No seguinte substitui o L por l mas como consideraste a string original outra vez, vai ficar 'OlA'. Quando passa para o A, substitui por a mas à string original, novamente. Ou seja, fica 'OLa'. Penso que é isto que se passa. Ou seja, o que está acontecer é o seguinte: a = 'OLA' ciclo: - i = 'O' -> b = 'o' -> c = string.replace('OLA','O','o') = 'oLA' - i = 'L' -> b = 'l' -> c = string.replace('OLA','L','l') = 'OlA' - i = 'A' -> b = 'a' -> c = string.replace('OLA','A','a') = 'OLa' Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now