list1 = ['192,3.2', '123,54.2']
yx = ([float(i) for i in list1])
print(list1)
This is the code I have and I am trying to learn for future reference on how to remove , within a list of string. I tried various things like mapping but the mapping would not work due to the comma within the num.
If you want to remove commas from a string use :
list1 = string.split(",")
the string variable contains your string input, you get your output in the form a list, join the list if you want the original string without the commas.
string_joined = "".join(list1)
string_joined will contain your string without the commas.
If you want your string to just remove the comma and retain the empty space at that position, your syntax :
string = string.replace(","," ")
Also, the fist two syntax I explained, can be shortened to a single syntax :
string = string.replace(",","")
Now if you want to iterate in your list of strings, consider each element(string) in your list one at a time :
for string in list1 :
<your codes go here>
Hope this answers what you are looking for.
we can do regex to remove the non-digits to get rid of other characters
import regex as re
print([float(re.sub("[^0-9|.]", "", s)) for s in list1])
without regex:
[float(s.replace(',','')) for s in list1 ]
output:
[1923.2, 12354.2]
Related
how can I convert a vertical string into a horizontal one in Python?
I tried:
result=astring.replace("\n", "")
but it doesn't do anything, it remains vertical..
The code is the following:
names = "".join(name).replace("\n","")
print(names)
where "names" is:
Federica
Silvio
Enrico
I would like:
Federica, Silvio, Enrico
x = """Federica
Silvio
Enrico"""
x.replace("\n",', ')
'Federica, Silvio, Enrico'
Your method is fundamentally wrong, when you apply a function, it combines a iterables with spaces in the middle. e.g.
" ".join("hello")
'h e l l o'
So when you call it on a string with no join value, the string is unchanged. Then you replace '\n' with '', which will flatten the string but not insert the comma.
If you have the names in a string format, for example:
names = """Federica
Silvio
Enrico"""
You can split the vertical string into an horizontal string using replace:
result = names.replace("\n", ", ")
Which results in:
print(results)
'Federica, Silvio, Enrico'
From this, I can say your approach was not wrong, maybe you were not storing the result of the replace? Replace does not modify the string but returns a new one with the operation performed.
I have a large list with strings and I would like to filter everything inside a parenthesis, thus I am using the following regex:
text_list = [' 1__(this_is_a_string) 74_string__(anotherString_with_underscores) question__(stringWithAlot_of_underscores) 1.0__(another_withUnderscores) 23:59:59__(get_arguments_end) 2018-05-13 00:00:00__(get_arguments_start)']
import re
r = re.compile('\([^)]*\)')
a_lis = list(filter(r.search, text_list))
print(a_lis)
I test my regex here, and is working. However, when I apply the above regex I end up with an empty list:
[]
Any idea of how to filter all the tokens inside parenthesis from a list?
Your regex is OK (though perhaps you don't want to capture the parentheses as part of the match), but search() is the wrong method to use. You want findall() to get the text of all the matches, rather than the indices of the first match:
list(map(r.findall, text_list))
This will give you a list of lists, where each inner list contains the strings which were inside parentheses.
For example, given this input:
text_list = ['asdf (qwe) asdf (gdfd)', 'xx', 'gdfw(rgf)']
The result is:
[['(qwe)', '(gdfd)'], [], ['(rgf)']]
If you want to exclude the parentheses, change the regex slightly:
'\(([^)]*)\)'
The unescaped parentheses within the escaped ones indicate what to capture.
I am making a dictionary application using argparse in Python 3. I'm using difflib to find the closest matches to a given word. Though it's a list, and it has newline characters at the end, like:
['hello\n', 'hallo\n', 'hell\n']
And when I put a word in, it gives a output of this:
hellllok could be spelled as hello
hellos
hillock
Question:
I'm wondering if there is a reverse or inverse \n so I can counteract these \n's.
Any help is appreciated.
There's no "reverse newline" in the standard character set but, even if there was, you would have to apply it to each string in turn.
And, if you can do that, you can equally modify the strings to remove the newline. In other words, create a new list using the current one, with newlines removed. That would be something like:
>>> oldlist = ['hello\n', 'hallo\n', 'hell\n']
>>> oldlist
['hello\n', 'hallo\n', 'hell\n']
>>> newlist = [s.replace('\n','') for s in oldlist]
>>> newlist
['hello', 'hallo', 'hell']
That will remove all newlines from each of the strings. If you want to ensure you only replace a single newline at the end of the strings, you can instead use:
newlist = [re.sub('\n$','',s) for s in oldlist]
I have a list which should contain string with a particular format or character i.e. {{str(x), str(y)},{str(x), str(y)}}. I tried to do string concat like: "{{"+str(x), str(y)+"},{"+str(x), str(y)+"}}" and append to list, but it gets surrounded by brackets: [({{str(x), str(y)}),({str(x), str(y)}})]
How can I get rid of the brackets or betterstill, is there a better approach to having a list without brackets like this: [{{string, string},{string, string}}]
The parentheses are because you're creating a tuple of three items:
"{{"+str(x)
str(y)+"},{"+str(x)
str(y)+"}}"
Try replacing those bare commas between str(x) and str(y) with +","+:
"{{"+str(x)+","+str(y)+"},{"+str(x)+","str(y)+"}}"
I know from the title you might think that this is a duplicate but it's not.
for id,row in enumerate(rows):
columns = row.findall("td")
teamName = columns[0].find("a").text, # Lag
playedGames = columns[1].text, # S
wins = columns[2].text,
draw = columns[3].text,
lost = columns[4].text,
dif = columns[6].text, # GM-IM
points = columns[7].text, # P - last column
dict[divisionName].update({id :{"teamName":teamName, "playedGames":playedGames, "wins":wins, "draw":draw, "lost":lost, "dif":dif, "points":points }})
This is how my Python code looks like. Most of the code is removed but essentially i am extracting some information from a website. And i am saving the information as a dictionary. When i print the dictionary every value has a bracket around them ["blbal"] which causes trouble in my Iphone application. I know that i can convert the variables to strings but i want to know if there is a way to get the information DIRECTLY as a string.
That looks like you have a string inside a list:
["blbal"]
To get the string just index l = ["blbal"] print(l[0]) -> "blbal".
If it is a string use str.strip '["blbal"]'.strip("[]") or slicing '["blbal"]'[1:-1] if they are always present.
you can also you replace to just replace the text/symbol that you don't want with the empty string.
text = ["blbal","test"]
strippedText = str(text).replace('[','').replace(']','').replace('\'','').replace('\"','')
print(strippedText)
import re
text = "some (string) [another string] in brackets"
re.sub("\(.*?\)", "", text)
# some in brackets
# works for () and will work for [] if you replace () with [].
The \(.*?\) format matches brackets with some text in them with an unspecified length. And the \[.*?\] format matches also but a square brackets with some text inside the brackets.
The output will not contain brackets and texts inside of them.
If you want to match only square brackets replace square brackets with the bracket of choice and vise versa.
To match () and [] bracket in one go, use this format (\(.*?\)|\[.*?\]:) joining two pattern with the | character.