I have this string:
string = '9x3420aAbD8'
How can I turn string into:
'023489ADabx'
What function would I use?
You can just use the built-in function sorted to sort the string lexicographically. It takes in an iterable, sorts each element, then returns a sorted list. Per the documentation:
sorted(iterable[, key][, reverse])
Return a new sorted list from the items in iterable.
You can apply that like so:
>>> ''.join(sorted(string))
'023489ADabx'
Since sorted returns a list, like so:
>>> sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']
Just join them together to create the desired string.
You can use the sorted() function to sort the string, but this will return a list
sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']
to turn this back into a string you just have to join it, which is commonly done using ''.join()
So, all together:
sorted_string = ''.join(sorted(string))
Related
Question : Write a Python program to remove the characters which have odd or even index
values of a given string.
I tried to make a copy of the list by deep copy .
I ran a loop from first list and checked for even then used pop method on second list to remove that specific index from the second list .
This code works for some inputs , I think mostly for those which doesn't have any repeated characters and doesn't work for others.
Code
#!/usr/bin/python3
import copy
list1 = input("Enter a string ")
list1 = list(list1)
list2 = copy.deepcopy(list1)
for i in list1:
if list1.index(i)%2 != 0:
list2.pop(list2.index(i))
print(list2)
The outputs for some samples are :
123456789 -> ['1', '3', '5', '7', '9'], qwertyuiop -> ['q', 'e', 't', 'u', 'o'], saurav -> ['s', 'u'], 11112222333344445555 -> ['1', '1', '1', '1', '2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5']
Read the documentation for index. It returns the index of the first occurrence of the given value. A simple print inside the loop will show you what's going on, in appropriate detail. This is a basic debugging skill you need to learn for programming in any language.
import copy
list1 = input("Enter a string ")
list1 = list(list1)
list2 = copy.deepcopy(list1)
for i in list1:
if list1.index(i)%2 != 0:
print(i, list1.index(i), list2.index(i))
list2.pop(list2.index(i))
print(list2)
print(list2)
output:
Enter a string google
o 1 1
['g', 'o', 'g', 'l', 'e']
o 1 1
['g', 'g', 'l', 'e']
e 5 3
['g', 'g', 'l']
['g', 'g', 'l']
... and that's your trouble. Fix your logic. You already know the needed index to save or remove. There is no need to extract the character, and then search for it again. You already know where it is.
Even better, simply slice the original string for the characters you want:
print(list1[::2])
Your problem is the list.index function. The documentation states that it "returns zero-based index in the list of the first item whose value is equal to x." Because you are calling it on list1 - and that is not modified - the result will always be list1.index('a') == 1 for example.
The correct solution would be to use enumerate. A further problem exists here - because you are indexing from an array that you have not modified, you indexes will be off after the first list.pop operation. Every item after the one removed will have been shifted by 1. To correct this, you could instead try building a list instead of emptying one:
#!/usr/bin/python3
list1 = input("Enter a string ")
list2 = []
for i, item in enumerate(list1):
if i % 2 == 0:
list2.append(item)
print(list2)
You don't need to iterate at all. Just reference the string elements directly.
st="123456789"
print('Odd: ', list(st[::2]))
print('Even: ', list(st[1::2]))
Output:
Odd: ['1', '3', '5', '7', '9']
Even: ['2', '4', '6', '8']
The method list.index(i) returns index in the list of the first item whose value is equal to i.
For example, "saurav".index('a') returns 1. when you call list2.pop(list2.index(i)) and you want to pop an a, it doesn't work well.
I think it can be simple using range as build-in function.
list1 = list(input("Enter a string "))
list2 = list()
for i in range(len(list1)):
if i % 2 == 0:
list2.append(list1[i])
print(list2)
It works with same way by following:
list1 = list(input("Enter a string "))
list2 = list()
for i in range(0, len(list1), 2):
list2.append(list1[i])
print(list2)
Also, you can use Extended Slices in Python 2.3 or above.
list1 = list(input("Enter a string "))
list2 = list1[::2]
print(list2)
Input:
we have given list
lst = ['a', '4', 'add', 'e', 'a', 'c0a8d202', '128', '4', '0', '32']
using regular expression find the hexvalue in given list
output:
index of hexvalue(In our case hexvalue is c0a8d202 then return the index 5)
Try this:
import re
lst = ['a', '4', 'add', 'e', 'a', 'c0a8d202', '128', '4', '0', '32']
pattern = re.compile(r'c[0-9a-fA-F]?')
for i in lst:
if re.search(pattern, i):
print(lst.index(i))
Note:
this is as per your desired output but i am agree with #Jean-François Fabre who said that what's wrong with lst.index('c0a8d202') ? what's the point of regular expressions here when you have the value already?
I have a Python dictionary in this format :
mongo = {
1: {'syno': ['a','b','c'], 'can': ['2','3','4']},
2 :{'syno': ['x','y','z'], 'can': ['6','7','8']},
}
and I have a list called syno_iter:
syno_iter = ['a','b','c','d','e']
Using a single value in syno_iter, let's suppose a. I want to get the values in the can in the mongo{} as in if the value a is available in the value of the value syno, we can return can.
We don't have any way of knowing the keys of mongo dict. Also as dictionaries are not iterable we can't use range thing.
To reiterate:
I want to do something like this-
for i in syno_iter:
if i in (mongo.values('syno')):
print mongo.values('can'(values()))
input - 'a'
output - ['2','3','4']
You can perform a lookup like that with:
Code:
def get_syno_values(data, lookup):
for row in data.values():
if lookup in row['syno']:
return row['can']
Test Code:
mongo = {
1: {'syno': ['a', 'b', 'c'], 'can': ['2', '3', '4']},
2: {'syno': ['x', 'y', 'z'], 'can': ['6', '7', '8']}
}
syno_iter = ['a', 'b', 'c', 'd', 'e']
print(get_syno_values(mongo, 'a'))
print(get_syno_values(mongo, 'y'))
Results:
['2', '3', '4']
['6', '7', '8']
sorry for the bad title. I am new to programming and I could not come up with a better description.
So, I have this code:
umw = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
def card_ranks(ranks):
"Return a list of the ranks, sorted with higher first."
for i in ranks:
if i in umw:
index = ranks.index(i)
ranks[index] = str(umw[i])
ranks.sort(reverse = True)
return ranks
print(card_ranks(['A', '3', '4', 'K'])) #should output [14, 13, 4, 3]
This gives me the following result:
['4', '3', '14', '13']
clearing the "reverse = True" gives the following:
['13', '14', '3', '4']
If i do something like that:
r = card_ranks(['A', '3', '4', 'K'])
r[0] -> gives me '4'
but this doesnt work again:
print(sorted(r)) -> gives me ['4', '3', '14', '13'] all over again.
So it seems, that the .sort() command views the 13 & 14 as a unit and the 3 & 4.
Could somebody explain why that is?
Thanks alot!
You're sorting them lexicographically, as strings rather than numbers. You could convert them to integers first, or you could expand your umw dictionary:
umw = {str(i): i for i in range(2, 10)}
umw.update({'T':10, 'J':11, 'Q':12, 'K':13, 'A':14})
def card_ranks(ranks):
return sorted(ranks, key=umw.get, reverse=True)
card_ranks(['A', '3', '4', 'K'])
# ['A', 'K', '4', '3']
This uses the dict.get method as a key function to guide the sorting without changing the values being sorted.
You are sorting strings where '11' comes before '3'. The following sorted call deals with the necessary type conversion:
def card_ranks(ranks):
return sorted((umw[c] if c in umw else int(c) for c in ranks), reverse=True)
>>> card_ranks(['A', '3', '4', 'K'])
[14, 13, 4, 3]
For every string in ranks, the generator expression produces the corresponding value in the umw dict or, as fallback, turns the string into an int, such that a proper numerical, non-lexicographical comparison is possible.
It does not see them as a unit, it compares the charakter for charakter:
'1'<'3'<'4', so the ranking is '13'<'14'<'3'<'4'
You want all of them to be numbers, so change the following lines:
ranks[index] = str(umw[i])
to
ranks[index] = umw[i]
and:
print(card_ranks(['A', '3', '4', 'K']))
to
print(card_ranks(['A', 3, 4, 'K']))
Because the list elements are string that's why
while sorting its taking in account every character i.e. every digit in the number
Which means every string char is sorted by its first character and then by its next character
Which means "233" < "3" and "1111" < "233"
umw = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
def card_ranks(ranks):
"Return a list of the ranks, sorted with higher first."
for i in ranks:
if i in umw:
index = ranks.index(i)
ranks[index] = str(umw[i])
ranks = list(map(int, ranks)) # The line to be added
ranks.sort(reverse = True)
return ranks
print(card_ranks(['A', '3', '4', 'K'])) #sh
You need to convert the list elements to int by ranks = list(map(int, ranks)) before sorting the list
ranks[index] = str(umw[i])
You are saving the values as strings instead of integers. And it is sorting them as strings.
Try
ranks[index] = int(umw[i])
I am writing a function in Python which can sort my list. The problem is that I don't want it in the same order that the sorted() method used. I tried using the sorting() method, but when I sort this string, which I it comes out like this:
0123456789abcdefghijklmnopqrstuvwxyzßàáäåæçèéêìíîñòóôöøùúüžα
The order I want it to be in is:
0123456789aàáäåæbcçdeèéêfghiìíîjklmnñoòóôöøpqrsßtuùúüvwxyzžα
Now, I've got a list like this (example):
list = ['x', 'h', 'ê', 'ø', '5', 'ž', 'z', 'α', '3', '1']
And I want so sort it. If I'd use the sorted() method, it would look like this:
['1', '3', '5', 'h', 'x', 'z', 'ê', 'ø', 'ž', 'α']
But I want it to be in the same order as the string I gave before.
The idea is to associate to each char the index in the specified order and use the indexes of the string chars to do the order comparison.
Note: only works with Python 3
Sort one char strings
ORDER = "0123456789aàáäåæbcçdeèéêfghiìíîjklmnñoòóôöøpqrsßtuùúüvwxyzžα"
# associate each char with the index in the string
# this makes sort faster for multiple invocations when compared with
# ORDER.index(c)
POS = {c:p for (p, c) in enumerate(ORDER)}
lst = ['x', 'h', 'ê', 'ø', '5', 'ž', 'z', 'α', '3', '1']
lst.sort(key = lambda c: POS[c])
# or, suggested by wim
lst.sort(key = POS.get)
Sort any length strings
class MyStrOrder:
def __init__(self, inner):
self.inner = inner
def __lt__(self, other):
for i in range(min(len(self.inner), len(other.inner))):
a = POS.get(self.inner[i])
b = POS.get(other.inner[i])
if a != b:
return a < b
return len(self.inner) < len(other.inner)
lst = ["abc", "ab", "aá"]
lst.sort()
print(lst)
lst = ["abc", "ab", "aá"]
lst.sort(key = MyStrOrder)
print(lst)
Outputs:
['ab', 'abc', 'aá']
['aá', 'ab', 'abc']