Related
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.
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(' ', '').
I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?
Use str.split():
>>> "42 0".split() # or .split(" ")
['42', '0']
Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.
Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:
>>> map(int, "42 0".split())
[42, 0]
In Python 3, map will return a lazy object. You can get it into a list with list():
>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
text = "42 0"
nums = [int(n) for n in text.split()]
l = (int(x) for x in s.split())
If you are sure there are always two integers you could also do:
a,b = (int(x) for x in s.split())
or if you plan on modifying the array after
l = [int(x) for x in s.split()]
This should work:
[ int(x) for x in "40 1".split(" ") ]
Of course you can call split, but it will return strings, not integers. Do
>>> x, y = "42 0".split()
>>> [int(x), int(y)]
[42, 0]
or
[int(x) for x in "42 0".split()]
Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:
import array
s = '42 0'
a = array.array('i')
for n in s.split():
a.append(int(n))
Edit: A more concise solution:
import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))
You can split and ensure the substring is a digit in a single line:
In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]
Given: text = "42 0"
import re
numlist = re.findall('\d+',text)
print(numlist)
['42', '0']
Use numpy's fromstring:
import numpy as np
np.fromstring("42 0", dtype=int, sep=' ')
>>> array([42, 0])
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.
I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?
Use str.split():
>>> "42 0".split() # or .split(" ")
['42', '0']
Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.
Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:
>>> map(int, "42 0".split())
[42, 0]
In Python 3, map will return a lazy object. You can get it into a list with list():
>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
text = "42 0"
nums = [int(n) for n in text.split()]
l = (int(x) for x in s.split())
If you are sure there are always two integers you could also do:
a,b = (int(x) for x in s.split())
or if you plan on modifying the array after
l = [int(x) for x in s.split()]
This should work:
[ int(x) for x in "40 1".split(" ") ]
Of course you can call split, but it will return strings, not integers. Do
>>> x, y = "42 0".split()
>>> [int(x), int(y)]
[42, 0]
or
[int(x) for x in "42 0".split()]
Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:
import array
s = '42 0'
a = array.array('i')
for n in s.split():
a.append(int(n))
Edit: A more concise solution:
import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))
You can split and ensure the substring is a digit in a single line:
In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]
Given: text = "42 0"
import re
numlist = re.findall('\d+',text)
print(numlist)
['42', '0']
Use numpy's fromstring:
import numpy as np
np.fromstring("42 0", dtype=int, sep=' ')
>>> array([42, 0])