How to remove apostrophes from a list in python? - python

I need to remove apostrophes -> ' <- from a list, within python, without using any add-ons, so only built in functions.
E.g. I need a list like:
lista = ['a', 'b', 'c', 'd']
into
lista = [ a, b, c, d]
I've tried using for with .replace or making the list into a string then replacing, but I haven't had anything work yet.
Any chance you could help?

You can use str.join() to concatenate strings with a specified separator.
For example:
>>> strings = ['A', 'B', 'C']
>>> print(', '.join(strings))
A, B, C
Furthermore, in your case, str.format() may also help:
>>> strings = ['A', 'B', 'C']
>>> print('strings = [{}]'.format(', '.join(strings)))
strings = [A, B, C]

You cannot remove apostrophes from a list because that's pretty much how you identify what a list is. However the apostrophes will not interfere with anything you do with the list. The apostrophes show that the elements are strings.

Related

Python: How to add single quotes to a long list

I want to know the quickest way to add single quotes to each element in a Python list created by hand.
When generating a list by hand, I generally start by creating a variable (e.g. my_list), assigning it to list brackets, and then populating the list with elements, surrounded by single quotes:
my_list = []
my_list = [ '1','baz','ctrl','4' ]
I want to know if there is a quicker way to make a list, however. The issue is, I usually finish writing my list, and then go in and add single quotes to every element in the list. That involves too many keystrokes, I think.
A quick but not effective solution on Jupyter NB's is, highlighting your list elements and pressing the single quote on your keyboard. This does not work if you have a list of words that you want to turn to strings, however; Python thinks you are calling variables (e.g. my_list = [1, baz, ctrl, 4 ]) and throws a NameError message. In this example, the list element baz would throw:
NameError: name 'baz' is not defined
I tried this question on SO, but it only works if your list already contains strings: Join a list of strings in python and wrap each string in quotation marks. This question also assumes you are only working with numbers: How to convert list into string with quotes in python.
I am not working on a particular project at the moment. This question is just for educational purposes. Thank you all for your input/shortcuts.
Yeah but then why not:
>>> s = 'a,b,cd,efg'
>>> s.split(',')
['a', 'b', 'cd', 'efg']
>>>
Then just copy it then paste it in
Or idea from #vash_the_stampede:
>>> s = 'a b cd efg'
>>> s.split()
['a', 'b', 'cd', 'efg']
>>>
The best way I found was:
>>> f = [10, 20, 30]
>>> new_f = [f'{str(i)}' for i in x]
>>> print(new_f)
['10', '20', '30']
You can take input as string and split it to list
For eg.
eg="This is python program"
print(eg)
eg=eg.split()
print(eg)
This will give output
This is python program
['This', 'is', 'python', 'program']
Hope this helps
It's been a while, but I think I've found a quick way following #U10-Forward's idea:
>>> list = ('A B C D E F G Hola Hello').split()
>>> print(list)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'Hola', 'Hello']

Python: replace an exact matching substring with variable

I have a list of strings like 'cdbbdbda', 'fgfghjkbd', 'cdbbd' etc. I have also a variable fed from another list of strings. What I need is to replace a substring in the first list's strings, say b by z, only if it is preceeded by a substring from the variable list, all the other occurrences being intouched.
What I have:
a = ['cdbbdbda', 'fgfghjkbd', 'cdbbd']
c = ['d', 'f', 'l']
What I do:
for i in a:
for j in c:
if j+'b' in i:
i = re.sub('b', 'z', i)
What I need:
'cdzbdzda'
'fgfghjkbd'
'cdzbd'
What I get:
'cdzzdzda'
'fgfghjkbd'
'cdzzd'
all instances of 'b' are replaced.
I'm new in it, any help is very welcome. Looking for answer at Stackoverflow I have found many solutions with regex based on word boundaries or with re either with str.replace based on count, but I can't use it as the lenght of the string and number of occurrences of 'b' can vary.
I think if you include j in the find and replace, you'll get what you want.
>>> for i in a:
... for j in c:
... i = re.sub(j+'b', j+'z', i)
... print i
...
cdzbdzda
fgfghjkbd
cdzbd
>>>
I added print i because your loop doesn't make in-place changes, so without that output, it's not possible to see what replacements were made.
You should simply use regular expressions with a positive lookbehind assertion.
Like this:
import re
for i in a:
for j in c:
i = re.sub('(?<=' + j + ')b', 'z', i)
The base case is:
re.sub('(?<=d)b', 'z', 'cdbbdbda')
You can use a list comprehension:
import re
a = ['cdbbdbda', 'fgfghjkbd', 'cdbbd']
c = ['d', 'f', 'l']
new_a = [re.sub('|'.join('(?<={})b'.format(i) for i in c), 'z', b) for b in a]
Output:
['cdzbdzda', 'fgfghjkbd', 'cdzbd']

Split the word by each character python 3.5 [duplicate]

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"]

How to insert quotes in list to separate items?

NEW QUESTION:
So I have the list a:
a = ["abcd"]
but I want it to be:
a = ["a","b","c","d"]
The list I'm working with is very long (200 terms long; not 4)
So how do I make Python put a quote (") after each letter so they're individual terms? Because I don't want to manually do this for all my lists.
In [4]: a = ["abcd"]
In [5]: list(a[0])
Out[5]: ['a', 'b', 'c', 'd']
For previous version:
In [3]: a = ["a,b,c,d"]
In [4]: a[0].split(",")
Out[4]: ['a', 'b', 'c', 'd']
#Akavall's answer is very good, but in case you are dealing with a list with possible whitespace around the commas like this:
my_list = ["a, b, c, d"]
You'll want to strip the resulting items like so:
new_list = [x.strip() for x in my_list.split(',')]
For a list like this:
my_list = ["abcd"]
you'll need a different approach. Just do:
new_list = list(a[0])

match the pattern at the end of a string?

Imagine I have the following strings:
['a','b','c_L1', 'c_L2', 'c_L3', 'd', 'e', 'e_L1', 'e_L2']
Where the "c" string has important sub-categories (L1, L2, L3). These indicate special data for our purposes that have been generated in a program based a pre-designated string "L". In other words, I know that the special entries should have the form:
name_Lnumber
Knowing that I'm looking for this pattern, and that I am using "L" or more specifically "_L" as my designation of these objects, how could I return a list of entries that meet this condition? In this case:
['c', 'e']
Use a simple filter:
>>> l = ['a','b','c_L1', 'c_L2', 'c_L3', 'd', 'e', 'e_L1', 'e_L2']
>>> filter(lambda x: "_L" in x, l)
['c_L1', 'c_L2', 'c_L3', 'e_L1', 'e_L2']
Alternatively, use a list comprehension
>>> [s for s in l if "_L" in s]
['c_L1', 'c_L2', 'c_L3', 'e_L1', 'e_L2']
Since you need the prefix only, you can just split it:
>>> set(s.split("_")[0] for s in l if "_L" in s)
set(['c', 'e'])
you can use the following list comprehension :
>>> set(i.split('_')[0] for i in l if '_L' in i)
set(['c', 'e'])
Or if you want to match the elements that ends with _L(digit) and not something like _Lm you can use regex :
>>> import re
>>> set(i.split('_')[0] for i in l if re.match(r'.*?_L\d$',i))
set(['c', 'e'])

Categories