+ 2
[If contains] formula in PY
How to build a program in Python, when I have given int, float... number ( eg. phone number) and I would like to skip one exact number and then proceed string wighout that number? Thanq
11 Antworten
+ 2
Přemek Janda
https://code.sololearn.com/c0gC6B4mwq9l/?ref=app
1.
len(string) ✔
len(integer)❌
2. for d in string, each d is string[i]
so the equivalence is
for i in range(0,len(string))
operate on string[i]
+ 4
Sure! Here's one way of doing it: I'd have to convert the integer to string so I can loop over its characters (secretly digits). I'd also have an auxiliary string variable initialized as the empty string.
Now, whenever the digit is not 5, I'd add it (concatenate) to my new string. Finally, I'd convert the new string back to integer.
myNum1 = 769857145
without5 = ""
for d in str(myNum1):
if d != '5':
without5 += d
without5 = int(without5)
print(without5)
There are more efficient methods, but this may be easier to see.
+ 3
Okay, so you want to remove all occurrences of the digit "5" from your integer? This is what I'd do: first convert it into a string, then use the str.replace() method to substitute all the "5" by "" (empty string), and then convert it back to int. Done together, it'd look like
myNum1 = 769857145
without5 = int(str(myNum1).replace("5", ""))
print(without5)
+ 3
I am starting with Py and I am glad you helped, thank you for your contribution. Now I could get over obstacle I was sitting in front of. :D
+ 2
I'll do that in second, just working on it.
+ 2
So I expressed my idea in this way. If you could help me, I would appeciate!
Thanq
https://code.sololearn.com/c0AB9XLXfyh4/?ref=app
+ 2
Oooh, it is quite simple when you know how to do it =D
Thank you so much for your support.
Btw is there any way to use for loop?
+ 2
just to add to ks's answer:
for-in loop is new way for high level, it works for arrays, and string is array of char.
if use for loop, the method to know size of array is len(array)
+ 2
ahh yes, now I finally properly understand. Thanq sir
+ 1
Could you please give a complete example? Thanks!
+ 1
Speary: I made a bit of adjustment to iterate up to last letter (in this case number).
myNum1 = 769857145
without5 = ""
for d in str(1,len(myNum1)):
if d != '5':
without5 += d
without5 = int(without5)
print(without5)