Separating a list into two - Python [duplicate] - python

This question already has answers here:
How can I partition (split up, divide) a list based on a condition?
(41 answers)
Closed 9 years ago.
For the following code:
print("Welcome to the Atomic Weight Calculator.")
compound = input("Enter compund: ")
compound = H5NO3
lCompound = list(compound)
I want to create two lists from the list lCompund. I want one list for characters and the other for digits. So that I may have something looking like this:
n = ['5' , '3']
c = ['H' , 'N' , 'O']
Can somebody please help by providing a simple solution?

Use a list comprehension and filter items using str.isdigit and str.isalpha:
>>> compound = "H5NO3"
>>> [c for c in compound if c.isdigit()]
['5', '3']
>>> [c for c in compound if c.isalpha()]
['H', 'N', 'O']

Iterate the actual string only once and if the current character is a digit, then store it in the numbers otherwise in the chars.
compound, numbers, chars = "H5NO3", [], []
for char in compound:
(numbers if char.isdigit() else chars).append(char)
print numbers, chars
Output
['5', '3'] ['H', 'N', 'O']

Related

Getting strings from list using python

Hi I am new to python I am trying to delete some unwanted characters and bring format
My lists are
List=
['2', '4a.', 'D', '__|5.', 'E|6.', 'F', '|7.', 'G', '—|8.'']
['9', '10.', "QRS(q,r", 's)', '11.', 'TUV/', '12.', "XYZ:"]
I want to get the list as follows
['D', 'E', 'F', 'G']
["QRS(q,r,s)", 'TUV/', "XYZ:"]
Here I want to delete numbers and alphanumeric ones
There are two challenges here
in the first list I had 'E|6.' I want to get E only string
in the second list I had "QRS(q,r", 's)' I want it as "QRS(q,r,s)" as only one string
Can anyone plz help me out thanks in advance
First you will need to differentiate between an special character and a alphabet character. For this you must have a list of limited alphabet characters -
import string
string.ascii_lowercase # returns all alphabets in lowercase.
Then you will need to iterate through the string in the list as to find possible alphabets in uppercase.
import string
List = ['2', '4a.', 'D', '__|5.', 'E|6.', 'F', '|7.', 'G', '—|8.'],['9', '10.', "QRS(q,r", 's)', '11.', 'TUV/', '12.', "XYZ:"]
what_you_need = []
for h in List:
for i in h:
for j in i:
if j.upper() in string.ascii_lowercase.upper():
what_you_need.append(j)
print(what_you_need)
you can try regular expression.
check below example:
import re
l1 = []
a = ['2', '4a.', 'D', '__|5.', 'E|16.', 'F', '|7.', 'G', '—|8.']
for idx, ele in enumerate(a):
if '(' in ele:
l1.append(ele + ',' + b[idx+1])
continue
elif ')' in ele:
pass
elif any([i.isdigit() for i in ele]):
g = re.findall(r"([A-Z])",ele)
if g:
l1.append(g[0])
else:
l1.append(ele)
In same way you can prepare regular expression for another list

How do I assign a character variable to a poistion in the string varible in python? [duplicate]

This question already has answers here:
Replacing one character of a string in python
(6 answers)
Closed 5 years ago.
I am working in Python right now.
My ch variable, which is the character variable has a character store in it, which has been entered by the user.
I also have a string variable (string1) in which I want to add the character without over-writing the string variable.
i.e I want to do string1[i]=ch, where i can be any position.
when i do this in python, it gives an error saying: 'str' object does not support item assignment.
here, string1[i]=ch, is in a while loop.
Is there a proper way of doing this? Please help.
str in python is immutable. That means, you can't assign some random value to a specific index.
For example, below is not possible:
a = 'hello'
a[2]= 'X'
There is an workaround.
make a list from the str.
mutate the specific index you wanted from that list.
form a str again from the list.
Like below:
>>> a = 'hello'
>>> tmp_list = list(a)
>>> tmp_list
['h', 'e', 'l', 'l', 'o']
>>> tmp_list[2] = 'X'
>>> tmp_list
['h', 'e', 'X', 'l', 'o']
>>>
>>> a = ''.join(tmp_list)
>>> a
'heXlo'

How do I convert user input into a list? [duplicate]

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 4 months ago.
I'm wondering how to take user input and make a list of every character in it.
magicInput = input('Type here: ')
And say you entered "python rocks"
I want a to make it a list something like this
magicList = [p,y,t,h,o,n, ,r,o,c,k,s]
But if I do this:
magicInput = input('Type here: ')
magicList = [magicInput]
The magicList is just
['python rocks']
Use the built-in list() function:
magicInput = input('Type here: ')
magicList = list(magicInput)
print(magicList)
Output
['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']
It may not be necessary to do any conversion, because the string supports many list operations. For instance:
print(magicInput[1])
print(magicInput[2:4])
Output:
y
th
Another simple way would be to traverse the input and construct a list taking each letter
magicInput = input('Type here: ')
list_magicInput = []
for letter in magicInput:
list_magicInput.append(letter)
or you can simply do
x=list(input('Thats the input: ')
and it converts the thing you typed it as a list
a=list(input()).
It converts the input into a list just like when we want to convert the input into an integer.
a=(int(input())) #typecasts input to int
using list comprehension,
magicInput = [_ for _ in input("Enter String:")]
print('magicList = [{}]'.format(', '.join(magicInput)))
produces
Enter String:python rocks
magicList = [p, y, t, h, o, n, , r, o, c, k, s]
You can use str.join() to concatenate strings with a specified separator.
Furthermore, in your case, str.format() may also help.
However the apostrophes will not interfere with anything you do with the list. The apostrophes show that the elements are strings.
Method 2:
magicInput = ','.join(input('Enter String: '))
print(f'\nmagicList: [{magicInput}]')

Python: Sort a list alphabetically, but with all lowercase letters given priority over capital letters [duplicate]

This question already has answers here:
Python sort strings alphabetically, lowercase first
(6 answers)
Closed 8 years ago.
I have a list of single digits (0-9) and single letters (aA-zZ), these are represented as strings. I'd like to sort
this list so that when sorted this list looks like below:
['0',..'1',..'2',..'a',..'b',..'c',....'z', 'A',.. 'B',.. 'C'.., 'Z']
so far every method of sorting that I've seen has paired the letters together such that 'A' follows 'a' and so on. Is there a way to sort this list such that capital letters are given the lowest priority?
You can use the key argument of sort or sorted to define whatever kind of ordering you like. Example:
>>> s = "123ABCabc"
>>> print sorted(s, key=lambda c: c.lower() if c.isupper() else c.upper())
['1', '2', '3', 'a', 'b', 'c', 'A', 'B', 'C']
Here, if a letter is lower case, we treat it as upper case for the purposes of sorting, and vice versa. characters with no case, such as digits, are unchanged.

How can I turn a string into a list in Python? [duplicate]

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 6 years ago.
How can I turn a string (like 'hello') into a list (like [h,e,l,l,o])?
The list() function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo

Categories

Resources