Format string in python list - python

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)+"}}"

Related

How to convert a vertical string to a horizontal one?

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.

How to get rid of whitespace in element of dictionary?

I am trying to extract only the string without whitespace of an element in a dictionary. This is how my element looks currently:
u'GYM-7874 '
I only want to extract the value without the whitespace so "GYM-7874" only so that I can compare it with another list of strings. I tried using the .strip() method to get rid of whitespaces but unfortunately that only works with string. How do I get rid of the white space and only extract the characters?
# json_ob is the string array of dictionary
title = json_ob[index]["title"]
title.strip()
strip() doesn't modify the string in place (strings are immutable in Python). You need to assign the result back to the variable.
title = title.strip()

How to execute it correctly?

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]

Confusion with string split method in python

Consider the following example
a= 'Apple'
b = a.split(',')
print(b)
Output is ['Apple'].
I am not getting why is it returning a list even when there is no ',' character in Apple
There might be case when we use split method we are expecting more than one element in list but since we are splitting based on separator not present in string, there will be only one element, wouldn't it be better if this mistake is caught during this split method itself
The behaviour of a.split(',') when no commas are present in a is perfectly consistent with the way it behaves when there are a positive number of commas in a.
a.split(',') says to split string a into a list of substrings that are delimited by ',' in a; the delimiter is not preserved in the substrings.
If 1 comma is found you get 2 substrings in the list, if 2 commas are found you get 3 substrings in the list, and in general, if n commas are found you get n+1 substrings in the list. So if 0 commas are found you get 1 substring in the list.
If you want 0 substrings in the list, then you'll need to supply a string with -1 commas in it. Good luck with that. :)
The docstring of that method says:
Return a list of the words in the string S, using sep as the delimiter string.
The delimiter is used to separate multiple parts of the string; having only one part is not an error.
That's the way split() function works. If you do not want that behaviour, you can implement your my_split() function as follows:
def my_split(s, d=' '):
return s.split(d) if d in s else s

String tokenization python

I wanted to split a string in python.
s= "ot.jpg/n"
I used str.split() but it gives me ['ot.jpg']. I want to get ot.jpg without brackets.
You want to use str.strip() to get rid of the newline. If you need to use split, it returns a list. To get the nth item from a list, index the list: ['foo', 'bar'][n].
Incidentally, naming your string str is a bad idea, since it shadows the built-in str function.
The return value of the split() method is always a list -- in this case, it's given you a single-element list theList = ['ot.jpg']. Like any list, you get what you want out of it by indexing it:
myString = theList[0]
sounds like you want replace.
s= "ot.jpg/n".replace("/n", "")
"ot.jpg"

Categories