Get two numbers from a string - python

I need to extract two numbers inside a string. They can look like this:
(0,0)
(122,158)
(1,22)
(883,8)
etc...
So I want to get the first number before the comma and the number after the comma and store them in variables. I can get the first number like this:
myString.split(',')[0][1:])
However, I can't figure out how to get the next number.
Thanks for the help everyone!

It should work with something like
myVar.split(',')[0][1:] # = 122 for the string in the second line
myVar.split(',')[1][:-1] # = 158 for the string in the second line
This should be the easiest way to do this

You could get rid of the parentheses, split the string, and convert each item to an int:
a, b = [int(x) for x in s[1:-1].split(',')]
Of course, if you absolutely sure about the string's format, and don't care about security, you could just eval the string:
a, b = eval(s)

You can use ast.literal_eval() to convert your string into a tuple. This will also take care about extra whitespace like '( 123, 158)'.
>>> from ast import literal_eval
>>> tup = literal_eval('(122,158)')
>>> tup[0]
122
>>> tup[1]
158
Or just:
>>> first, second = literal_eval('(122,158)')

Multi assignment, stripping the parentheses and splitting will do:
a, b = myString.lstrip('(').rstrip(')').split(',')
# a, b = map(int, (a, b))

myVar.split(',')[1][:-1])
will get you the second number

The simplest one-liner would be
a, b = (myString[1:-1].split(',')[0], myString[1:-1].split(',')[1])
Gets rid of the parentheses, then splits at the comma.

Related

convert List of List to list float

I have a list of list of coordinate with data type of float for example something like this
[[106.4372634887695, -6.3303128514375], [106.4372634887695, -6.3299716218919], [106.4376068115234, -6.3299716218919]]
and I want to convert it so the inside bracket would be gone and replaced only by comma. and the comma inside the deepest bracket would be replaced too by space
and the final format would be something like
((106.4372634887695 -6.3303128514375, 106.4372634887695 -6.3299716218919, 106.4376068115234 -6.3299716218919))
Is there a good way to solve this?
I tried to use map and join but i didn't succeeded
You can flatten your array by using:
flatten = [elm for bracket in data for elm in bracket]
It's like:
arr = []
for bracket in data:
for x in bracket:
arr.append(x) #or arr += [x]
If you just want to sum brackets, do:
final = [a + b for a,b in arr]#b is -|b|, it's negative, then a+b is the same as 106.xxx - 6.xxx
The format you want is not the representation of any type which exists in Python. If you want it as a string, then, turn to string processing:
pairs = [[106.4372634887695, -6.3303128514375], [106.4372634887695, -6.3299716218919], [106.4376068115234, -6.3299716218919]]
stringified = ', '.join(' '.join(map(str,pair)) for pair in pairs)
parenthesized = f'(({stringified}))'

During string concatenation, how to add delimiter only if variable is set?

How to add the delimiter only if that variable has a value, in the below code, I am trying to avoid 2 underscores like: foo_bar__baz, a,b,d will be always set, only c is optional, is there a more pythonic way?
>>> a_must='foo'
>>> b_must='bar'
>>> c_optional=''
>>> d_must='baz'
>>>
>>> f'{a_must}_{b_must}_{c_optional}_{d_must}' if c_optional else
f'{a_must}_{b_must}_{d_must}'
'foo_bar_baz'
Its in python3.6
You can write the conditional inside the f-string itself:
f'{a_must}_{b_must}_{c_optional+"_" if c_optional else ""}{d_must}'
Output:
'foo_bar_baz'
To be a little more flexible, something like this would work:
variables = [a_must, b_must, c_optional, d_must]
'_'.join([x for x in variables if x])
You can build a list of tokens and use str.join to join the list into a string with _ as the delimiter:
tokens = [a_must, b_must]
if c_optional:
tokens.append(c_optional)
tokens.append(d_must)
print('_'.join(tokens))
Your solution works fine, it just needed a little formatting. I added the print statement for testing.
a_must='foo'
b_must='bar'
c_optional=''
d_must='baz'
if c_optional:
result = f'{a_must}_{b_must}_{c_optional}_{d_must}'
else:
result = f'{a_must}_{b_must}_{d_must}'
print(result)

python parsing a string

I have a list with strings.
list_of_strings
They look like that:
'/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
I want to part this string into:
/folder1/folder2/folder3/folder4/folder5/exp-* and put this into a new list.
I thought to do something like that, but I am lacking the right snippet to do what I want:
list_of_stringparts = []
for string in sorted(list_of_strings):
part= string.split('/')[7] # or whatever returns the first part of my string
list_of_stringparts.append(part)
has anyone an idea? Do I need a regex?
You are using array subscription which extracts one (eigth) element. To get first seven elements, you need a slicing [N:M:S] like this:
>>> l = '/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
>>> l.split('/')[:7]
['', 'folder1', 'folder2', 'folder3', 'folder4', 'folder5', 'exp-*']
In our case N is ommitted (by default 0) and S is step which is by default set to 1, so you'll get elements 0-7 from the result of split.
To construct your string back, use join():
>>> '/'.join(s)
'/folder1/folder2/folder3/folder4/folder5/exp-*'
I would do like this,
>>> s = '/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
>>> s.split('/')[:7]
['', 'folder1', 'folder2', 'folder3', 'folder4', 'folder5', 'exp-*']
>>> '/'.join(s.split('/')[:7])
'/folder1/folder2/folder3/folder4/folder5/exp-*'
Using re.match
>>> s = '/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file'
>>> re.match(r'.*?\*', s).group()
'/folder1/folder2/folder3/folder4/folder5/exp-*'
Your example suggests that you want to partition the strings at the first * character. This can be done with str.partition():
list_of_stringparts = []
list_of_strings = ['/folder1/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file', '/folder1/exp-*/folder2/folder3/folder4/folder5/exp-*/exp-*/otherfolder/file', '/folder/blah/pow']
for s in sorted(list_of_strings):
head, sep, tail = s.partition('*')
list_of_stringparts.append(head + sep)
>>> list_of_stringparts
['/folder/blah/pow', '/folder1/exp-*', '/folder1/folder2/folder3/folder4/folder5/exp-*']
Or this equivalent list comprehension:
list_of_stringparts = [''.join(s.partition('*')[:2]) for s in sorted(list_of_strings)]
This will retain any string that does not contain a * - not sure from your question if that is desired.

Split string by hyphen

I have a strings in the format of feet'-inches" (i.e. 18'-6") and I want to split it so that the values of the feet and inches are separated.
I have tried:
re.split(r'\s|-', `18'-6`)
but it still returns 18'-6.
Desired output: [18,6] or similar
Thanks!
Just split normally replacing the ':
s="18'-6"
a, b = s.replace("'","").split("-")
print(a,b)
If you have both " and ' one must be escaped so just split and slice up to the second last character:
s = "18'-6\""
a, b = s.split("-")
print(a[:-1], b[:-1])
18 6
You can use
import re
p = re.compile(ur'[-\'"]')
test_str = u"18'-6\""
print filter(None,re.split(p, test_str))
Output:
[u'18', u'6']
Ideone demo
A list comprehension will do the trick:
In [13]: [int(i[:-1]) for i in re.split(r'\s|-', "18'-6\"")]
Out[13]: [18, 6]
This assumes that your string is of the format feet(int)'-inches(int)", and you are trying to get the actual ints back, not just numbers in string format.
The built-in split method can take an argument that will cause it to split at the specified point.
"18'-16\"".replace("'", "").replace("\"", "").split("-")
A one-liner. :)

Split a string in python

a="aaaa#b:c:"
>>> for i in a.split(":"):
... print i
... if ("#" in i): //i=aaaa#b
... print only b
In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value?
The following can replace your if statement.
for i in a.split(':'):
print i.partition('#')[2]
>>> a="aaaa#b:c:"
>>> a.split(":",2)[0].split("#")[-1]
'b'
a = "aaaa#b:c:"
print(a.split(":")[0].split("#")[1])
I'd suggest from: Python Docs
str.rsplit([sep[, maxsplit]])
Return a list of the words in the string, using sep as the delimiter
string. If maxsplit is given, at most maxsplit splits are done, the
rightmost ones. If sep is not specified or None, any whitespace string
is a separator. Except for splitting from the right, rsplit() behaves
like split() which is described in detail below.
so to answer your question yes.
EDIT:
It depends on how you wish to index your strings too, it looks like Rstring does it from the right, so if your data is always "rightmost" you could index by 0 (or 1, not sure how python indexes), every time, rather then having to do a size check of the returned array.
do you really need to use split? split create a list, so isn't so efficient...
what about something like this:
>>> a = "aaaa#b:c:"
>>> a[a.find('#') + 1]
'b'
or if you need particular occurence, use regex instead...
split would do the job nicely. Use rsplit only if you need to split from the last '#'.
a="aaaa#b:c:"
>>> for i in a.split(":"):
... print i
... b = i.split('#',1)
... if len(b)==2:
... print b[1]

Categories