Python List Replace [duplicate] - python

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python and Line Breaks
In Python I know that when your handling strings you can use "replace" to replace a certain character in a string. For example:
h = "2,3,45,6"
h = h.replace(',','\n')
print h
Returns:
2
3
45
6
Is there anyway to do this with a list? For example replace all the "," in a list with "\n"?
A list like:
h = ["hello","goodbye","how are you"]
"hello"
"goodbye"
"how are you"
And the Script should output something like this:
Any suggestions would be helpful!

Looking at your example and desire, you can use the str.join and this is probably what you want
>>> h
['2', '3', '45', '6']
>>> print '\n'.join(str(i) for i in h)
2
3
45
6
similarly for your second example
>>> h = ["hello","goodbye","how are you"]
>>> print '\n'.join(str(i) for i in h)
hello
goodbye
how are you
If you really wan't the quotation mark for strings you can use the following
>>> h = ["hello","goodbye","how are you"]
>>> print '\n'.join('"{0}"'.format(i) if isinstance(i,str) else str(i) for i in h)
"hello"
"goodbye"
"how are you"
>>>

You could use list comprehension for that:
>>> search = 'foo'
>>> replace = 'bar'
>>> lst = ['my foo', 'foo', 'bip']
>>> print [x.replace(search, replace) for x in lst]
['my bar', 'bar', 'bip']

In a list like your h = [2,5,6,8,9], there really are no commas to replace in the list itself. The list contains the items 2, 5 and so on, the commas are merely part of the external representation to make it easier to separate the items visually.
So, to generate some output form from the list but without the commas, you can use any number of techniques. For instance, to join them all up into a single string without commas, use:
"".join([str(x) for x in h])
This will evaluate to 25689.

for each in h: print each
In 3.x:
for each in h: print(each)
A list is simply a representation of data. You can only affect the way it looks in the output.

You can replace the ',' in the string because the ',' is part of the string itself but you cannot replace the ',' in a list because it is not an item in the list rather it is what is used by python for delineating different items in such a list together with the opening and closing square brackets. It is just like asking if you could replace the '"' used in creating the string. On the other hand if the ',' is an item in the list and you want to replace it with a newline item then you could use list comprehensions like:
['\n' if x=="," else x for x in yourlist]
or if you want to print each item on a single line you could use:
for item in list:
print item

Related

How to remove free space from list of integer , I want final result in list rather than string [duplicate]

I have this code here. I want to print a list without spaces. Here l is a list with 3 elements that I am trying to print:
>>> l=[]
>>> l.append(5)
>>> l.append(6)
>>> l.append(7)
>>> print(l)
I get in the output:
[5, 6, 7]
but I want to get:
[5,6,7]
What should I add to the syntax in append or in print to print the list without spaces?
You need to use something like:
print('[{0}]'.format(','.join(map(str, l))))
You can modify the result if it isn't too big:
print(repr(l).replace(' ', ''))
You could convert it to a string and then replace the spaces. E.g:
print ("{}".format(l)).replace(' ', '')
Join the list elements.
print("[" + ",".join([str(i) for i in l]) + "]")

How to add a word before the last word in list?

Hello I'm new to this programming language
I wanted to add the word 'and' before the last item in my list.
For example:
myList = [1,2,3,4]
If I print it the output must be like:
1,2,3 and 4
Here is one way, but I have to convert the int's to strings to use join:
myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]
print(",".join(smyList), 'and', myList[-1])
gives:
1,2,3 and 4
The -1 index to the list gives the last (rightmost) element.
This may not be the most elegant solution, but this is how I would tackle it.
define a formatter function as follows:
def format_list(mylist)
str = ''
for i in range(len(mylist)-1):
str.append(str(mylist[i-1]) + ', ')
str.append('and ' + str(mylist[-1]))
return str
then call it like this
>>> x = [1,2,3,4]
>>> format_list(x)
1, 2, 3, and 4
You can also use string formating:
l = [1,2,3,4]
print("{} and {}".format(",".join(str(i) for i in l[:-1]), l[-1]))
#'1,2,3 and 4'
Using join (to join list elements) and map(str,myList) to convert all integers inside list to strings
','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1])
#'1,2,3 and 4'
Your question is misleading, if you are saying "How to add a word before the last word in list?" it means you want to add 'and' string before last item in the list , while many people are giving answer using .format() method , You should specify you want 'and' for printing or in list for further use of that result :
Here is list method according to your question :
myList = [1,2,3,4]
print(list((lambda x,y:(x+['and']+y))(myList[:-1],myList[-1:])))
output:
[1, 2, 3, 'and', 4]

How to add commas at required positions in the given string in Python?

How to add commas at required positions in the given string in Python?
In my case, the positions are not fixed.
Example: My requirement is to add the commas after 5th, 8th, 11th, 13th in an input string = "hello Python program"
My expected output would be: hello, Py,tho,n p,rogram
Is there any simplest way to achieve this in Python?
Actually I need to apply a comma on 590 positions in my file record and then process it.
Strings are immutable in python, so if you're going to perform modifications on the string, it would be more efficient to convert the string to a list first. You can then call str.join on the string once you're done.
string = list("hello Python program") # somewhat counterintuitive a name
for i, j in enumerate([5, 8, 11, 13]):
string.insert(i + j, ',')
print(''.join(string))
'hello, Py,tho,n ,program'
>>> string = "hello Python program"
>>> commas = [5, 8, 11, 13]
One way (probably the most efficient):
>>> ','.join(string[i:j] for i, j in zip([None] + commas, commas + [None]))
'hello, Py,tho,n ,program'
Another (for this one, commas should be a set for efficiency):
>>> ''.join(c + ',' * (i in commas) for i, c in enumerate(string, 1))
'hello, Py,tho,n ,program'
Another:
>>> a = list(string)
>>> for i in reversed(commas):
a.insert(i, ',')
>>> ''.join(a)
'hello, Py,tho,n ,program'
Use this function:
def insertc(index,s,c):
return s[:index]+c+s[index:]
s='hello Python program'
j=0
for i in [5,8,11,13]:
s=insertc(i+j,s,',')
j+=1
print(s)

Splitting lists at the commas

Currently I have a long list that has elements like this:
['01/01/2013 06:31, long string of characters,Unknown'].
How would I split each element into:
['01/01/2013 06:31], [long string of characters],[Unknown]? Can I even do that?
I tried variable.split(","), but I get "AttributeError: 'list' object has no attribute 'split'".
Here's my code:
def sentiment_analysis():
f = open('C:\path', 'r')
write_to_list = f.readlines()
write_to_list = map(lambda write_to_list: write_to_list.strip(), write_to_list)
[e.split(',') for e in write_to_list]
print write_to_list[0:2]
f.close()
return
I'm still not getting it, I'd appreciate any help!
Solution
You are given this:
['01/01/2013 06:31, long string of characters,Unknown']
Alright. If you know that there is only this one long string in this list, just extract the only element:
>>> x = ['01/01/2013 06:31, long string of characters,Unknown']
>>>
>>> y = x[0].split(",") # extract only element and split by comma
>>> print(y) # list of strings, with one depth
['01/01/2013 06:31', ' long string of characters', 'Unknown']
Now for whatever reasons, you actually want each eletent of the outer list to be a list with one string in it. That is easy enough to do - simply use map and anonymous functions:
... # continuation from snippet above
...
>>> z = map(lambda s: [s], y) # encapsulates each elem of y in a list
>>> print(z)
[['01/01/2013 06:31'], [' long string of characters'], ['Unknown']]
There you have it.
One-Liner Conclusion
No list comprehensions, no for loops, no generators. Just really simple functional programming and anonymous functions.
Given original list l,
res = map(lambda s: [s],
l[0].split(","))
List comprehension!
>>> variable = ['01/01/2013 06:31, long string of characters,Unknown']
>>> [x.split(',') for x in variable]
[['01/01/2013 06:31', ' long string of characters', 'Unknown']]
But wait, that's nested more than you wanted...
>>> itertools.chain.from_iterable(x.split(',') for x in variable)
<itertools.chain object at 0x109180fd0>
>>> list(itertools.chain.from_iterable(x.split(',') for x in variable))
['01/01/2013 06:31', ' long string of characters', 'Unknown']

Append a portion of a string to a list

I was wondering how one can append a portion of a string to a list? Is there an option of both appending based on the position of characters in the string, and another option that is able to take a specific character of interest? For instance, If I had the string "2 aikjhakihaiyhgikjewh", could I not only append the part of the string that was in positions 3-4 but also append the "2" as well? I'm a beginner, so I'm still kinda new to this python thing. Thanks.
You can use slicing to reference a portion of a string like this:
>>> s = 'hello world'
>>> s[2:5]
'llo'
You can append to a list using the append method:
>>> l = [1,2,3,4]
>>> l.append('Potato')
>>> l
[1, 2, 3, 4, 'Potato']
Best way to learn this things in python is to open an interactive shell and start typing commands on it. I suggest ipython as it provides autocomplete which is great for exploring objects methods and properties.
You can append a portion of a string to a list by using the .append function.
List = []
List.append("text")
To append several parts of the string you can do the following:
List = []
String = "2 asdasdasd"
List.append(String[0:2] + String[3:5])
This would add both sections of the string that you wanted.
Use slicing to accomplish what you are looking for:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst
This runs as:
>>> mystr = "2 aikjhakihaiyhgikjewh"
>>> lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
>>> print lst
['2', 'i', 'k']
>>>
Slicing works by taking certain parts of an object:
>>> mystr
'2 aikjhakihaiyhgikjewh'
>>> mystr[0]
'2'
>>> mystr[-1]
'h'
>>> mystr[::-1]
'hwejkighyiahikahjkia 2'
>>> mystr[:-5]
'2 aikjhakihaiyhgi'
>>>
You are describing 2 separate operations: slicing a string, and extending a list. Here is how you can put the two together:
In [26]: text = "2 aikjhakihaiyhgikjewh"
In [27]: text[0], text[3:5]
Out[27]: ('2', 'ik')
In [28]: result = []
In [29]: result.extend((text[0], text[3:5]))
In [30]: result
Out[30]: ['2', 'ik']

Categories