How to convert a vertical string to a horizontal one? - python

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.

Related

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]

How can I merge these two lines of code into one (Python 3.X)?

text = ''.join(sorted([x for x in input()]))
text = text.replace('+', '', text.count('+'))
I just it love it when you can do all sort of things in one line with Python.
text = ''.join(sorted(input())).replace('+', '')
OR
text = ''.join(sorted(input().replace('+', '')))
You don't need to use list comprehension. Just pass the input() to sorted(); sorted support any iterable.
the 3rd argument to str.replace() is redundant. Because the code is replacing all occurences of +.
Ok, this is not exactly the same code, but in this case result is similar:
text = ''.join(sorted([x for x in input() if x != '+']))
Instead of creating whole string and then replacing one character, you can simply remove it in first list comperhesion.

Format string in python list

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

Save the index value of blanks in a string to a tuple in Python 3

How can I save the index position of spaces in a text sentence to a tuple so I can reconvert the sentence back after removing the strings?
For example in this text the are spaces which causes an error as there are no space in the ascii alphabet. So I want to remove the spaces, convert and then reformat spaces back to original position.
import string
text = "This is the text I wish to convert"
alpha = [c for c in list(string.ascii_lowercase)]
alphaTup = tuple(alpha)
myConvert = list(text.lower())
blanks = myConvert.index(' ')
print(blanks)
# This doesn't work
for item in myConvert:
#find index of item in alphaTup and return value at index + 1
newLet = alphaTup[alphaTup.index(item) + 1]
print(newLet)
If you want to know the indices of all the blanks, I suppose using enumerate could be helpful:
blank_indices = [i for i, c in enumerate(text) if c == ' ']
(This gives a list instead of a tuple, but it's not hard to get the tuple if you really need it...)
With that said, looping over a string character-by-character, is not the best way to accomplish most tasks in python. It's hard for me to tell exactly what transform you're trying to perform on the string, so I'm not sure how to advise better ...

Reconstituting Strings in Python

I would like to do something like:
temp=a.split()
#do some stuff with this new list
b=" ".join(temp)
where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do this without removing newlines?
I assume in your third line you mean join(temp), not join(a).
To split and yet keep the exact "splitters", you need the re.split function (or split method of RE objects) with a capturing group:
>>> import re
>>> f='tanto va\nla gatta al lardo'
>>> re.split(r'(\s+)', f)
['tanto', ' ', 'va', '\n', 'la', ' ', 'gatta', ' ', 'al', ' ', 'lardo']
The pieces you'd get from just re.split are at index 0, 2, 4, ... while the odd indices have the "separators" -- the exact sequences of whitespace that you'll use to re-join the list at the end (with ''.join) to get the same whitespace the original string had.
You can either work directly on the even-spaced items, or you can first extract them:
>>> x = re.split(r'(\s+)', f)
>>> y = x[::2]
>>> y
['tanto', 'va', 'la', 'gatta', 'al', 'lardo']
then alter y as you will, e.g.:
>>> y[:] = [z+z for z in y]
>>> y
['tantotanto', 'vava', 'lala', 'gattagatta', 'alal', 'lardolardo']
then reinsert and join up:
>>> x[::2] = y
>>> ''.join(x)
'tantotanto vava\nlala gattagatta alal lardolardo'
Note that the \n is exactly in the position equivalent to where it was in the original, as desired.
You need to use regular expressions to rip your string apart. The resulting match object can give you the character ranges of the parts that match various sub-expressions.
Since you might have an arbitrarily large number of sections separated by whitespace, you're going to have to match the string multiple times at different starting points within the string.
If this answer is confusing to you, I can look up the appropriate references and put in some sample code. I don't really have all the libraries memorized, just what they do. :-)
It depends in what you want to split.
For default split use '\n', ' ' as delimitador, you can use
a.split(" ")
if you only want spaces as delimitador.
http://docs.python.org/library/stdtypes.html#str.split
I don't really understand your question. Can you give an example of what you want to do?
Anyway, maybe this can help:
b = '\n'.join(a)
First of all, I assume that when you say
b = " ".join(a)
You actually mean
b = " ".join(temp)
When you call split() without specifying a separator, the function will interpret whitespace of any length as a separator. I believe whitespace includes newlines, so those dissapear when you split the string. Try explicitly passing a separator (such as a simple " " space character) to split(). If you have multiple spaces in a row, using split this way will remove them all and include a series of "" empty strings in the returned list.
To restore the original spacing, just make sure that you call join() from the same string which you used as your separator in split(), and that you don't remove any elements from your intermediary list of strings.

Categories