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.
Related
This question already has an answer here:
What is the difference between a list of a single iterable `list(x)` vs `[x]`?
(1 answer)
Closed 3 years ago.
Sorry for this question, but I do not understand why the difference between the following results when adding an element to the list as a list itself to other list:
list_a=[]
list_b=['HELLO','WORLD']
for word in list_b:
list_a.append([word])
print("Append to dist_list single word: ", list_a)
Output: Append to list_a: [['HELLO'], ['WORLD']]
list_a=[]
list_b=['HELLO','WORLD']
for word in list_b:
list_a.append(list(word))
print("Append to list_a: ", list_a)
output: Append to list_a: [['H', 'E', 'L', 'L', 'O'], ['W', 'O', 'R', 'L', 'D']]
When you perform list() to a string, the string gets turned into a list that's separated for each individual value. For example:
a = 'string'
b = list(a)
b = ['s','t','r','i','n','g']
Therefore the difference comes because in the first case you are appending two items (both being strings) and in the second one, you are appending the string previously turned into a list with the logic explained above, hence you've appended a list for each string. This is the differnece in the results you are getting. First case add two strings, second case add two lists.
This question already has answers here:
Converting a list to a set changes element order
(16 answers)
Closed 4 years ago.
I want to print the elements of the set consecutively, so I wrote the following code:
s='dmfgd'
print(set(s))
However, this code shows the output as:
set(['m', 'd', 'g', 'f'])
but, I want output like:
set(['d','m','f','g'])
Any help will be appreciated.
Set is unordered. You can instead use a list of dict keys to emulate an ordered set if you're using Python 3.6+:
print(list(dict.fromkeys(s)))
This outputs:
['d', 'm', 'f', 'g']
Python set is unordered collections of unique elements
Try:
s='dmfgd'
def removeDups(s):
res = []
for i in s:
if i not in res:
res.append(i)
return res
print(removeDups(s))
Output:
['d', 'm', 'f', 'g']
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"]
This question already has answers here:
IndexError: string index out of range:
(5 answers)
Closed 2 years ago.
Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop.
I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?
>>> name = "Chris"
>>>
>>> my_list = []
>>>
>>> for key, value in enumerate(name):
... my_list.append(value[key])
... print (my_list)
...
The error I'm receiving:
['C']
Traceback (most recent call last):
File "<pyshell#7>", line 2, in <module>
my_list.append(value[key])
IndexError: string index out of range
What you are missing is that value is a single element string. Indexing at positions != 0 will result in an IndexError; during your first iteration that's what happens.
If you want to create it with your for loop, just append the value immediately:
for key, value in enumerate(name):
my_list.append(value)
Of course, enumerate is by no means required here, this can be simplified by calling list and supplying the string in question; Python will then create a list containing the contents of the string for you:
my_list = list(name)
For Python 3.x you can also unpack in a list literal with *:
my_list = [*name]
In all supplied snippets, the result of the operations is ['C', 'h', 'r', 'i', 's'] as required.
name = 'Chris'
my_list = list(name)
print(my_list)
Input: ['C', 'h', 'r', 'i', 's']
For one in each time:
for letter in name:
print(letter)
You are enumerating over a string ("Chris") which means that key and value will hold the following values during the iteration:
0 "C"
1 "h"
2 "r"
3 "i"
4 "s"
value[key] in the first iteration is ok, it returns 'C'.
In the second iteration, the index 1 is out of range for string "h".
What you probably want to do is this:
for i, value in enumerate(name):
my_list.append(value)
print (my_list)
An alternative way, to reach your goal:
>>>name ="Chris"
>>>list(name)
['C', 'h', 'r', 'i', 's']
For your example:
When iterating through a string in python, no enumeration is required.
>>>name = "Chris"
>>>my_list = []
>>>for i in name:
... my_list.append(i)
>>>my_list
['C', 'h', 'r', 'i', 's']
change my_list.append(value[key]) to my_list.append(value) in your code
This question already has an answer here:
Why is the join built-in having no influence on my code?
(1 answer)
Closed 6 years ago.
I am not sure why this join() performed on a list doesn't work.
Here is my code:
list_1 = ['a', 'b', 'c']
print (list_1)
' '.join(list_1)
print (list_1)
And this is what is returned when I run it:
['a', 'b', 'c']
['a', 'b', 'c']
join() doesn't modify or reassign the list in place, instead it returns the string that it creates:
list_1 = ['a', 'b', 'c']
print (list_1)
list_1_string = ' '.join(list_1)
print (list_1_string)
From the str.join(iterable) docs:
Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
You are not storing the result of join...
list_1 = ' '.join(list_1)
str.join(<iterable>) returns a str. It doen't mutate the list to a str(!). Do the following,
s = " ".join(list_1)
print(s)