Let's suppose that I have this string a='12345&&&4554444'
, how do I read only the numbers of said string without the need to do it with a loop since the only way I know is by looping through the list.
variable=str('')
for i in a:
if i!='&':
variable+=i
print(variable)
whose output would be:
1234545564444
Is there another way to do this??
Thank you!
If you only have digits and "&" and you want to remove all "&" characters you can
str.replace
simply use:More general options that work regardless of what characters you have mixed with the digits there are more, among them:
Regular expressions:
or using
re.sub:
In this case we instruct you to substitute an empty string (remove) any character that is not a digit (
\D
).Use a set (
set
) with the allowed characters to filter the data using a generator and a conditional taking advantage of the efficiency of searches in hash tables:str.isdigit
, which returnsTrue
if all characters in a string are digits:str.tranlate
:str.tranlate
receives a "table" that has Unicode ordinal values as an index and that for each one returns the value with which it should be replaced. The "table" can be any object that implements the method__getitem__
, such as a dictionary. The classTransTable
is initialized with a sequence of characters that are going to be allowed, each time its method is called__getitem__
it returns the same character if it is among the allowed ones orNone
otherwise (which implies that this character is eliminated bytranslate
).One note, concatenating strings (
cad = "foo" + "bar"
) is especially inefficient given its immutable nature, which means creating a new object each time it's done.str.join
It is a better alternative, especially if it is used together with a generator, since we avoid the construction of intermediate objects.Both
str.tranlate
regular expressions and using a set have the advantage of being able to very simply specify which characters we want to keep in the string.Yes, there are several ways, but the first thing to say is that when building a string character by character, as you do with
variable
, the approach you follow of concatenating letters at the end with the operator+=
is inefficient due to the way in which python manage the strings.Since a string for python is immutable, when you add something to it it actually creates a new string by copying the old one plus whatever you added to it. The previous string is discarded. This repeated many times implies copying the string many times, so a list is usually used instead, which does allow you to add things to the end (with
.append()
) instead of copying everything every time you add something.Finally the resulting list can be converted to a string with the operator
str.join()
Now let's see different ways to solve the problem
using lists
Basically your code, but changing the string
variable
to a list:list comprehensions _
You can use list comprehensions which is a feature of the python language that allows you to replace loops with a line of code. Not only is it more compact, and in my opinion more readable, but it is also slightly faster:
functional programming
If you come from the world of Lisp or have a mathematical mind, you may be interested in the functional paradigm, which also allows you to eliminate loops by changing them for functions that receive iterables and other functions as parameters and internally apply the function in question to each value of the iterable.
This modality does not allow to do anything that cannot also be done with list comprehensions and in fact the creator of Python prefers comprehensions so that the functional features of python (like
map()
,filter()
and others) have been relegated to a separate module (functools
) instead from being part of the language as they were in version 2.I personally find the syntax of list comprehensions more elegant, but it's up to you. This would be the functional modality:
In this case it
filter()
expects two parameters. The second is an iterable. The first is a function that will apply to each element of the iterable. If the function returnstrue
, it accepts the element. If you don't reject it. What it returns is another iterable with the accepted elements (which I then convert to a string with"".join()
)The first parameter that I pass to
filter()
is a lambda , which is nothing more than a type of ultra-simple function whose code consists only of an expression whose evaluation will be the return value. They are written by putting the wordlambda
, the name of the parameter (in this casei
), a colon and the "body" of the function, which is the expression to be evaluated, whose result is what will be returned. No control statement can be put in this function. Just an expression.Specific String Handling Functions
To replace sub-strings, extract parts of them that follow a certain pattern, "translate" each character by a different one, etc. Python supplies many methods in the class
str
, and in the modulere
(regular expressions). I do not put examples here because there are already in other answers.