Converting lat/lon strings to tuple - python

I want to create a function that converts lat/lon string into tuples.
This is what I have tried but it is giving me an error "could not convert string to float".
Thanks for your help.
def convert(d):
d.replace(" ", "")
return [tuple(map(float,coords.split(','))) for coords in d.split()]
convert("-122.4194, 37.7749")
Output:
ValueError: could not convert string to float:

Use ast.literal_eval like this: [docs]
>>> import ast
>>>
>>> d = "-122.4194, 37.7749"
>>> print(ast.literal_eval(d))
(-122.4194, 37.7749)
>>> type(ast.literal_eval(d))
<class 'tuple'>
This method will only work if you expect the input to look like a tuple like is given in your example convert("-122.4194, 37.7749")
So for your code if you want to use convert(d)
import ast
def convert(d):
return ast.literal_eval(d)
convert("-122.4194, 37.7749")
Result:
>>> x = convert("-122.4194, 37.7749")
>>> type(x)
<class 'tuple'>
>>> x
(-122.4194, 37.7749)

This problem is that you are splitting d on whitespace with d.split() in your list comprehension. For your example input this is unnecessary. Just split on the comma:
def convert(d):
d.replace(" ", "")
return tuple(map(float,d.split(',')))
coords = convert("-122.4194, 37.7749")
print(coords)
Since float() ignores whitespace anyway, you don't need to call d.replace():
def convert(d):
return tuple(map(float,d.split(',')))
coords = convert("-122.4194, 37.7749")
print(coords)

Why don't you just do this? This removes the need to replace the ' ' with '' and also simplifies the work you were doing in your function. It also doesn't require any extra packages. Actually, you float() will strip the leading space from the second point in your tuple.
def convert(d):
return tuple(map(float,d.split(',')))
convert("-122.4194, 37.7749")
Note that in cases when you do want to remove whitespace from the beginning and ending of a string, you can use strip() instead of replace(' ', '').

Related

I am able to parse the log file but not getting output in correct format in python [duplicate]

How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
It's very useful for beginners to know
why join is a string method.
It's very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although #Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
We can also use Python's reduce function:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
We can specify how we join the string. Instead of '-', we can use ' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
If you have a mixed content list and want to stringify it, here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to the list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
If you want to generate a string of strings separated by commas in final result, you can use something like this:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

Issue with join(str(x))

x = [1,2,3]
print '-'.join(str(x))
Expected:
1-2-3
Actual:
(-1-,- -2-,- -3-)
What is going on here?
Because calling str on the list in its entirety gives the entire list as a string:
>>> str([1,2,3])
'[1, 2, 3]'
What you need to do is cast each item in the string to an str, then do the join:
>>> '-'.join([str(i) for i in x])
'1-2-3'
You sent x to str() first, putting the given delimiter between each character of the string representation of that whole list. Don't do that. Send each individual item to str().
>>> x = [1,2,3]
>>> print '-'.join(map(str, x))
1-2-3

removing the ' ' and the spaces in the return output python3

i am trying out a function where you have to use def function(a,b,c,d)
a is a string so i did
a = str(a)
b is an integer so i did
b= int(b)
c is also a string;
c = str(c)
and d is a boolean (all i know about boolean is True or False); so
d = True
i wanted to change the order of the elements into
[c,a,b,d]
and i assigned this to result = [c,a,b,d]
when i used the return function
return str(result), (because i want to return a string)
i ended up with
"[ 'c', 'a', b, d]"
i have tried everything to get rid of the ' ' and also the spacing because it should really look like
'[c,a,b,d]'
what can i do to remove it?
def elem(tree,year,ident,passed):
tree = str(tree)
year = int(year)
ident = str(ident)
passed = True
result = [ident,tree,year,passed]
return str(result)
this is what i;ve done so far
so if i wanted to test the code i have so far in the python shell i end up with
>>> elem("pine",2013,"1357",True)
"['1357', 'pine', 2013, True]"
the output that i want from this is
'[1357,pine,2013,True]'
sorry if i didn't provide enough. this is all i have right now.. and sorry for not doing good formatting for the posting..
Just create the string you want from the data structure you have:
>>> '[{},{},{},{}]'.format('c','a',2,True)
'[c,a,2,True]'
>>> '[{},{},{},{}]'.format(*['c','a',2,True])
'[c,a,2,True]'
>>> '[{},{},{},{}]'.format(*['1357', 'pine', 2013, True])
'[1357,pine,2013,True]'
Or edit the string representation of a data structure to be what you want it to be:
>>> str(['c', 'a', 2, True])
"['c', 'a', 2, True]"
>>> str(['c', 'a', 2, True]).replace("'","").replace(' ','')
'[c,a,2,True]'
In either case, the final outer ' go away when you print the string:
>>> print('[{},{},{},{}]'.format(*['c','a',2,True]))
[c,a,2,True]
>>> print(str(['c', 'a', 2, True]).replace("'","").replace(' ',''))
[c,a,2,True]
>>> li=['1357', 'pine', 2013, True]
>>> print('[{},{},{},{}]'.format(*li))
[1357,pine,2013,True]
The reason you have " " is because it's a string. You returned the string representation of the list, when infact you should just be returning the list:
return result
With the string you have, you can safely convert it back to a list with ast.literal_eval:
import ast
...
myresult = function(a, b, c, d)
print ast.literal_eval(myresult)
return "[" + ",".join(result) + "]"
When you call str(result) it gives a string representation of the object result. What that string actually looks like depends on the implementation of the class that the object belongs to (it calls the special method __str__ in the class to do the conversion).
Since the object (result) belongs to class list then you get the standard string representation for a list. You cannot (sensibly) change the list class, so you need to create a different representation.
In your sample code, I'm puzzled why you are doing the conversions. Why convert year to an int when you want a string representation? Why set passed to True when it is a parameter? Anyway:
def elem(tree, year, ident, passed):
passed = True
result = "[%s,%s,%d,%s]" % (ident, tree, year, passed)
return result
print(elem("pine", 2013, "1357", True))
Gives:
[1357,pine,2013,True]

How to extract string from python list?

Assuming a python array "myarray" contains:
mylist = [u'a',u'b',u'c']
I would like a string that contains all of the elements in the array, while preserving the double quotes like this (notice how there are no brackets, but parenthesis instead):
result = "('a','b','c')"
I tried using ",".join(mylist), but it gives me the result of "a,b,c" and eliminated the single quotes.
You were quite close, this is how I would've done it:
result = "('%s')" % "','".join(mylist)
What about this:
>>> mylist = [u'a',u'b',u'c']
>>> str(tuple(map(str, mylist)))
"('a', 'b', 'c')"
Try this:
result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))
>>> l = [u'a', u'b', u'c']
>>> str(tuple([str(e) for e in l]))
"('a', 'b', 'c')"
Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses. Finally, calling str on the result of that should return the list of elements with the single quotes enclosed in parentheses.
What about repr()?
>>> repr(tuple(mylist))
"(u'a', u'b', u'c')"
More info on repr()
Here is another variation:
mylist = [u'a',u'b',u'c']
result = "\"{0}\"".format(tuple(mylist))
print(result)
Output:
"('a', 'b', 'c')"

How to concatenate (join) items in a list to a single string

How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
It's very useful for beginners to know
why join is a string method.
It's very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although #Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
We can also use Python's reduce function:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
We can specify how we join the string. Instead of '-', we can use ' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
If you have a mixed content list and want to stringify it, here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to the list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
If you want to generate a string of strings separated by commas in final result, you can use something like this:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

Categories

Resources