I have the string '1234.12'
and I want to split it into two lists: [1234]
and [12]
.
The only way I know is to make the whole string into a list by using .split()
with a comprehension: [n.split() for n in '1234.12']
, which gives me:
[['1'], ['2'], ['3'], ['4'], ['.'], ['1'], ['2']]
s = '1234.12'
a,b = ([int(x)] for x in s.split(".",1))
print(a,b)
Or just do it in 2 parts, map to int and just wrap in lists after:
s = '1234.12'
a, b = map(int,s.split(".", 1))
a,b = [a],[b]
Which will both give you the two numbers cast to int and wrapped in lists:
a -> [1234]
b -> [12]
You can split the string with dot and the n use map
function to convert the result to list:
>>> map(list,s.split('.'))
[['1', '2', '3', '4'], ['1', '2']]
And of you want the result as int
you can use int
function within map
:
>>> map(int,s.split('.'))
[1234, 12]
Note that in this case you can access to the numbers with a simple indexing and don't need to put each of them within a list.
To explain why what you were trying wasn't working,
n.split() for n in '1234.12'
is effectively equivalent to
for n in '1234.12':
n.split()
When you iterate over a string like that, you end up getting the individual characters, so we can also say that is equivalent to:
for n in ('1', '2', '3', '4', '.', '1', '2'):
n.split()
So since the split
was only given a single character at a time, it wasn't functional. You want to move the split to the string itself:
n for n in '1234.12'.split()
At which point you don't need the comprehension anymore.
'1234.12'.split()
The last piece was explained elsewhere... split
, by default, splits on whitespace, so to tell it to split on a period instead:
'1234.12'.split('.')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.