Hello, I have the following doubt:
Let's say I have the following list of numbers and I want to display the elements of this list one by one but editing the way the elements are output:
telefonos = ["9191211412","6641211412","9941211412","1264511412"]
for x in telefonos:
print(x[0:2],"-",x[2:6],"-",x[6:10], sep="")
I have this and it's fine:
91-9121-1412
66-4121-1412
99-4121-1412
12-6451-1412
Now what I want to do and it doesn't come out, is to put or replace those results in a new list or simply in the same one that I had with the new format that I kept before with the print. I need help!!
EDIT:
With the answers they gave me I was able to fix it very easily like this:
telefonos = []
for x in telefonos:
telefonos.append([f"{x[0:2]}-{x[2:6]}-{x[6:10]}"]))
If you're using Python 3.6 onwards I recommend using formatted string literals, it's much more efficient and more readable in my opinion:
Simply each
{}
indicates a replacement target, which is replaced by the result of evaluating the expression it contains. The rest, splitting the original string, is done by slicing just like you already do.to create a new list use exactly the same thing in a
for
, using list compression it would be simply:Example:
The above line is equivalent (although much less efficient) to:
If you wanted to modify it in-place, use the index to reassign the new string:
Is this how it works for you?