pazzdzioh
pazzdzioh

Reputation: 71

How to hide part of string in python

I am just wondering if there is such possibility to hide somehow part of string in python. I am not talking about slicing. I am talking about situation where I have "1somestring," while printing I obtain "somestring". 1 before somestring should be visible for python but not displayable. Or It could be nice to have some kind of indicator glued to string. What I want to achieve is custom sorting. I have list of strings and I want to sort them by addition of digits in front of them. Sorting will proceed basing on digits thus behind digits I can insert whatever I want, but I don’t want to have digits visible. Thanks for answers in advance.

Upvotes: 0

Views: 7908

Answers (5)

Neamtu93
Neamtu93

Reputation: 31

I will ask to the question in the title: Let's say that our string is:

ceva="123Password"

If you want to hider first 2:

ceva=ceva[2:]

ceva will be '3Password'

Now let's play with list of strings:

lista=["abc","ghi","def"]
for _,x in enumerate(sorted(lista)):
    print(str(_)+x)

0abc
1def
2ghi

or

lista=["abc","ghi","def"]
for _,x in enumerate(sorted(lista)):
    lista[_]=str(_)+x
>>> lista
['0abc', '1def', '2ghi']

Upvotes: 0

Lewis Fogden
Lewis Fogden

Reputation: 524

You could store them in a list, with each entry consisting of a tuple indicating order (low to high), then the string. The default sorting on this list would place them in order.

words = [(1,"blah"), (3,"wibble"), (2,"splop")]
words.sort()
print(words)
[(1, 'blah'), (2, 'splop'), (3, 'wibble')]

print(" ".join(word[1] for word in words))
blah splop wibble

Upvotes: 2

Rockybilly
Rockybilly

Reputation: 4510

You can define a print function other than the built-in one. So this might not be exactly seek, what you want to do is better explained in the comments. But this is also a way.

def print2(string):
    print "".join(letter for letter in string if letter.isalpha())

In you script, if you restrict the usage of the print function and only use the one you defined. It could be a solution.

Upvotes: 0

donkopotamus
donkopotamus

Reputation: 23206

This does not require "hiding" information in your string. It simply requires combining them with your other information (the numbers) at sorting time, and that can be done in many ways. Here's one:

# my strings, and the order I'd like them to have
my_strings = ["how", "there", "hello", "you", "are"]
my_ordering = [2, 1, 0, 3, 4]

# sort them
sorted_strings = [x for _, x in sorted(zip(my_ordering, my_strings))]
print(sorted_strings)

Upvotes: 0

Stidgeon
Stidgeon

Reputation: 2723

I think something simple like a situation where you have a list of things like:

['1something', '2more', '3another']

is to modify each element using an empty substitution, then print:

import re

for item in list:
    charonly = re.sub('[0-9]','', item)
    print charonly

Upvotes: 0

Related Questions