Change Python string

Asked

Viewed 1,690 times

0

I’m making a program to sort the numbers entered (I can’t just use a sort algorithm), searching saw that it is not possible to change strings in python, is there any way to do this? Or maybe use list instead of string?

entrada = "32415"

for i in range(entrada):
    if entrada[i] > entrada[i+1]:
        aux = entrada[i]
        entrada[i] = entrada[i+1]
        entrada[i+1] = aux

print(entrada) 

2 answers

4


First of all, remember that python has much more efficient sorting algorithms already implemented in the language, simply calling a function to sort:

entrada = ''.join(sorted(entrada))

But to answer your question: yes, lists are mutable, you can convert your string into a list:

entrada = "32415"
entrada = list(entrada)

Your sorting algorithm has some problems, it seems that you are trying to use the "bubble method", however you need to return to position whenever there is change, in which case it would be better to use the while instead of for:

i = 1
while i < len(entrada):
    if entrada[i] < entrada[i-1]:
        entrada[i], entrada[i-1] = entrada[i-1], entrada[i]
        i = max(1, i - 1)
    else:
        i += 1

Then at the end you can convert the result back to string using the join:

entrada = ''.join(entrada)
print(entrada)

The result:

12345

1

Hello, all right? D
I don’t know if you are studying algorithms for sorting or want a practical Python solution, but I will follow the second option.
To sort your variable entree, a possibility could be the following:

entrada = '32415'
# Nos dois próximos comandos a string vai virar uma lista.
# Em ordem crescente.
entrada = sorted(entrada)
# Ordem decrescente.
entrada = sorted(entrada, reverse=True)
# Converter de volta para string.
entrada = ''.join(str(a) for a in entrada)

I don’t know if that’s what you want, but I hope so :D

  • 1

    Two tips: 1) you do not need to convert the character to string at the end, since it is already a character; 2) change the variable name, have entrada as a result is very confusing, ideally leave unchanging input and set others to the result.

  • Oops, thank you so much for the tip! I’m still beginner and I will follow this yes for sure :D

Browser other questions tagged

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