0

I have a string variable which have integer value and pick all integer value from list or string

EXAMPLE

a = 'This is user code 8466823 and passkey is 1258746'
sample = "1234567890"
b = []
for i in a:
    if i in sample:
        b.append(i.replace(" ", "\n"))

b = "".join(b)
print(b)

output like this 84668231258746 but Expect like this 8466823 and 1258746 in next or in seperate line

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Ehsan Rahi
  • 65
  • 7

2 Answers2

0

You're never appending newline to b because there's no space in sample, so if i in sample: will never succeed for the space characters.

Add a separate check for that instead of using i.replace().

for i in a:
    if i == " ":
        b.append("\n")
    elif i in sample:
        b.append(i)
Barmar
  • 669,327
  • 51
  • 454
  • 560
0

To do this, you need to know that the two strings are separate. Your problem is that you lost that information when you looped through your input string character-by-character, and then appended only the digits to the list.

In your case, b looks like this after the for i in a loop:

 ['8', '4', '6', '6', '8', '2', '3', '1', '2', '5', '8', '7', '4', '6']

Instead, you should loop over words by doing a.split() first. Then, you can check if each word is completely numeric, and append the entire word to the list.

for i in a.split():
    if i.isnumeric():
        b.append(i)

print("\n".join(b)) 

which gives the output

8466823
1258746

If your sample has more characters than just the digits, you can replace i.isnumeric() with a check that all characters in i belong in sample like so:

for i in a.split():
    if all(char in sample for char in i):
        b.append(i)
Pranav Hosangadi
  • 17,542
  • 5
  • 40
  • 65