This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 2 years ago.
I tried using all the methods suggested by others but its not working.
methods like str.split(), lst = list("abcd") but its throwing error saying [TypeError: 'list' object is not callable]
I want to convert string to list for each character in the word
input str= "abc" should give list = ['a','b','c']
I want to get the characters of the str in form of list
output - ['a','b','c','d','e','f'] but its giving ['abcdef']
str = "abcdef"
l = str.split()
print l
First, don't use list as a variable name. It will prevent you from doing what you want, because it will shadow the list class name.
You can do this by simply constructing a list from the string:
l = list('abcedf')
sets l to the list ['a', 'b', 'c', 'e', 'd', 'f']
First of all, don't use list as name of the variable in your program. It is a defined keyword in python and it is not a good practice.
If you had,
str = 'a b c d e f g'
then,
list = str.split()
print list
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Since split by default will work on spaces, it Will give what you need.
In your case, you can just use,
print list(s)
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Q. "I want to convert string to list for each character in the word"
A. You can use a simple list comprehension.
Input:
new_str = "abcdef"
[character for character in new_str]
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Just use a for loop.
input:::
str="abc"
li=[]
for i in str:
li.append(i)
print(li)
#use list function instead of for loop
print(list(str))
output:::
["a","b","c"]
["a","b","c"]
Related
I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]
print('list length', len(lists))
splited=[]
splited1=lists[0][0].split(',')
print(splited1) #['a', 'b', 'c', 'h']
splited2=lists[1][0].split(',')
print(splited2) #['d', 'e', 'f', 'g']
listcomb=[splited1,splited2]
print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]
This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)
sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
print(sepcomb)
I'm having problems with splitting the letters and then joining them in a new list. Pls help
Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
to
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb.append(sep)
Method-2
sepcomb = list(i[0].split(',') for i in lists)
You can simply do the following:
final=[splinted1]+[splinted2]
Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]
Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]
listcomb = []
for each in lists:
splited = each[0].split(',')
listcomb.append(splited)
print(listcomb)
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 4 years ago.
I am trying to print a list like a string:
list = ['a', 'b', 'c', 'd', 'e', 'f']
the output I want it to be;
abcdef
You should use the join() method, in python, join() returns a string in which the string elements of sequence have been joined by str separator.
str = ''
sequence = ['a', 'b', 'c', 'd', 'e', 'f']
print str.join(sequence)
You can pass any list or tuple as sequence.
If you just want to print it, you can make use of the end parameter of print. It defaults to "\n" and is what is printed at the end of the string passed to it:
for i in list:
print(i, end="")
If you actually want the string, you can just add them together(not in all python versions):
string=""
for i in list:
sting+=i
If you know how many items are in your list:
string=list[0]+list[1]+list[2]+list[3]+list[4]
or:
print(list[0],list[1],list[2],list[3],list[4], sep="")
(sep is what is printed between each string, defaults to " ", However the two above are quite messy.
I have two lists
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
I have a variable with random text in it.
var = 'backout'
I want to convert all letters in the variable that exist in list1 to the letters in list2.
expectedOutput = 'edfkout'
Is there a way to do this?
You want to use str.translate using a translation table from string.maketrans (This is str.maketrans in Python 3)
from string import maketrans
s1 = 'abc'
s2 = 'def'
table = maketrans(s1, s2)
print('backout'.translate(table))
Edit:
Note that we have to use strings instead of lists as our arguments to maketrans.
We can map the keys to values using a zip()wrapped with dict() and then iterate the letters and map them to their corresponding ones with themselves being the default (in case not found):
keys = ['a', 'b', 'c']
values = ['d', 'e', 'f']
mapper = dict(zip(keys, values))
var = 'backout'
output = "".join([mapper.get(k, k) for k in var])
print(output) # edfkout
Convert each char to its ascii value using map(ord,list1) and do the 1-1 mapping b/w list1 and list2 using zip
tbl = dict(zip(map(ord,list1), map(ord,list2)))
var.translate(tbl)
Output:
edfkout
For people who prefer shorter but more complicated solution (instead of using the translate() method), here it is:
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
var = 'backout'
trans_dict = dict(zip(list1, list2))
out_string = ''.join([trans_dict.get(ch, ch) for ch in var])
The explanation:
dict(zip(list1, list2))
creates the {'a': 'd', 'b': 'e', 'c': 'f'} dictionary.
trans_dict.get(ch, ch)
The 1st argument is a key - if it is found in keys, we obtain its value: trans_dict[ch]
The 2nd argument is a default value - used if the first argument is not found in keys. We obtain ch.
[trans_dict.get(ch, ch) for ch in var]
is a list comprehension - something as creating a list from the empty list, appending next and next element in the for loop.
''.join(list_of_string)
is a standard way for concatenating individual elements of the list (in our case, the individual characters).
(Instead of the empty string there may be an arbitrary string - it is used for delimiting individual elements in the concatenated string)
I have two lists that I want to combine for csv output:
alist = ['a', 'b', 'c']
blist = ['d', 'e', 'f']
However, I want the output for the csv to format like this:
clist = ['a', 'b', 'c', 'd e f']
such that the last entry extended of the list contains the list of "blist", but will not be comma separated. Unfortunately, what I have been trying instead gives me:
clist = ['a', 'b', 'c', 'def']
Is this what you are after?
clist = alist + [" ".join(blist)]
otherwise I think what you are after doesn't make sense, or you need to explain better what you want... Given python syntax, 'x' 'y' 'z' is 'xyz'.
I am trying to concatenate items in a list onto a string.
list = ['a', 'b', 'c', 'd']
string = ''
for i in list:
string.join(str(i))
You don't need a loop:
items = ['a', 'b', 'c', 'd']
result = "".join(items)
Note that it's a bad idea to use list as the name of a variable, because that prevents you from using list to mean the built-in type.
Is this what you are looking for?
>>> my_list = ['a', 'b', 'c', 'd']
>>> "".join(my_list)
'abcd'
You shouldn't use list as a variable name, since this will shadow the built-in class list.