Draw Inside a Python String

Asked

Viewed 1,550 times

0

I am doing a program in Python, whose statement is as follows::

Create a function that takes a string and turns some of the characters into uppercase and others into lowercase.

I need the user to enter the amount of draws he wants to make, for example: If he wants to draw 3 numbers, the program will draw 3 numbers between 0 and Len(string), then the program checks whether the string in the drawn position is uppercase or minuscule, If it’s a capital case, turn it into a minuscule, and if it’s a minuscule, turn it into a capital... I made this program in C and wanted to do in python too, but I’m not getting it, I did so far: (but it’s giving error)

from random import randint
frase = str(input("Digite a String: "))
while True:
    qntd_sorteio = int(input("Quantos números deseja sortear? "))
    if qntd_sorteio >= 1:
        break
    else:
        print("O número precisa ser um número real...")
pos = 0
while qntd_sorteio > 0:
    pos = randint(0, len(frase))
    if frase[pos].isupper():
       frase[pos].lower()
    elif frase[pos].islower():
       frase[pos].upper()
    qntd_sorteio -= 1
print(frase)

I don’t know what the mistake, I don’t know how to turn, if anyone can help me...

  • Don’t know what the bug is? It didn’t appear when you tried to run the code?

  • Appears "Indentationerror: Unexpected indent" in the line of the "if phrase[pos]. isupper():"

  • https://www.geeksforgeeks.org/isupper-islower-lower-upper-python-applications/

  • This is indentation error. Inside your while there is a if indented wrong. In Python it is trivial that you properly format all lines of code.

  • @Maurydeveloper This he has done in his code, I did not understand what the purpose of quoting this link...

  • Oh yes, sorry, that I had noticed but I had not fixed here, but the problem continues, I do the raffles and everything and when I will print the string, it printa without any changes

  • My only problem is that the changes are not being made, they go into Ifs and Elses, but when I do the attribution, to change it to a greater or smaller size, they don’t change

  • Error not syntax @Andersoncarloswoss https://repl.it/KnottyNanoPacket

  • I just need to know how I turn, for example: "Q", into "q", because the assignment I am doing is not correct...

Show 4 more comments

2 answers

2


The main problem with the answer is that you used the methods lower and upper as if they were object modifiers. In Python a string is immutable and, by definition, cannot be modified. In this case, the methods lower and upper return a new string with the changed box.

Other points are:

  1. You don’t have to do str(input(...)); the return of function input will always be a string.
  2. I believe that it does not make sense to draw the values this way, because there will be the possibility of drawing the same number more than once generating an unexpected output; if I informed 4 characters and he drew twice the same value I would have only 2 modified characters.

Another way to solve it would be:

from random import sample

frase = input('Informe a frase: ')
quantidade = int(input('Informe a quantidade: '))
posições = sample(range(len(frase)), quantidade)

resultado = ''

for posição, letra in enumerate(frase):
  if posição in posições:
    letra = letra.swapcase()
  resultado += letra

print(resultado)

See working on Repl.it

  • The expression sample(range(len(frase)), quantidade) will generate a sequence of N numbers between 0 and len(frase)-1, including, at random and without repetition;

  • With the aid of enumerate each letter of the sentence together with its position is traversed; when the position of the letter is a drawn position, the letter is concatenated into a new result string.

  • With the function swapcase the letter box is reversed; that is, if it is lowercase it will be returned uppercase and vice versa.

  • His point 2 is correct, in the exercise he also asked that the numbers drawn were not equal, hence I would do something like "if draw not in list", then I would do the rest of the code, I didn’t put this part of the statement here in the stack because it would be something too big to explain, but Voce is right

  • 1

    @Brennocarvalho The function sample receives two parameters: a population (sequence of values) and a quantity k. The return will be a new sequence of k population values taken randomly and without repetition.

  • Thank you very much, I managed to understand right and with a code much smaller than I was doing before :)

  • 1

    @Brennocarvalho Just see that I didn’t treat the entrance at quantidade in the answer, as you already did this in the question I assumed you already knew how to do. If you want to know more, I have already commented on this in Accept only numerics in input

  • yes, I noticed, but this is a little indifferent, here my code I’ve done too, but thank you even :D

1

# encoding: utf-8
from random import Random
frase = raw_input("Digite a String: ")
while True:
  try:
    qntd_sorteio = int(raw_input("Quantos números deseja sortear? "))
  except ValueError:
    print "Deve ser um número inteiro!"
  if qntd_sorteio < 0 or qntd_sorteio > len(frase):
    print "Deve ser entre 0 e", len(frase)
  else:
    break

posicoes = Random().sample(xrange(len(frase)), qntd_sorteio)

lista_letras = list(frase)

for i in posicoes:
  lista_letras[i] = lista_letras[i].upper() if lista_letras[i].islower() else lista_letras[i].lower()

print ''.join(lista_letras)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.