-1

I've learned python for a few months and I have a question.

Example I have a string s='string_123', I need to get "123" from s.

As I know, python provided some ways:

This question look likely with: Python: Extract numbers from a string

But, it mostly compare split() with regex. I need to know for detail of each way.

s.split("_")[-1]
s.partition("_")[2]
s[7:]

So which way is the best above? Or do we have any way else better than all?

Lê Tư Thành
  • 1,063
  • 2
  • 10
  • 19

3 Answers3

2

The difference between split and partition is that partition will only split on the first occurrence of the given separator and returns that separator itself as well.

split will return an array of strings, separating the string based on the locations of the given separator and not including the separator in the array.

Take the string "a+b+c+d".

"a+b+c+d".split("+") # (= ["a", "b", "c", "d"])
"a+b+c+d".partition("+") # (= ("a", "+", "b+c+d"))

You can only use the s[7:] when you know that the underscore is exactly at position 6. This will also return everything after the underscore, so let's say we want to split the previous string based on the "+" sign, knowing that the plus is on position 1, we'll use the array notation:

"a+b+c+d"[2:] # (= "b+c+d")

You can combine that with find:

i = "a+b+c+d".find("+")
"a+b+c+d"[i+1:] # ( = "b+c+d")
SBylemans
  • 1,764
  • 13
  • 28
0

You could also do:

>>> import re
>>> re.findall(r'\d+', s)[0]
'123'

This uses regular expression to identify the digits in your string, and split them into a list. [0] selects the first instance of digits that appear in the string.

ycx
  • 3,155
  • 3
  • 14
  • 26
0

From any aspect, you need to tell it is the best like how fast, memory used, complexity. So, it depends on your needs. For example, the simplest way is to use:

s='string_123'
end = None
print(s[7:end])

If you don't know where is the _ use this

s='string_123'
index=0
for i in s:
   index=index+1
   if i=='_':
    break;


end = None
print(s[index:end])

For split the string

print(s.split('_'))

code here:https://repl.it/repls/LoneJuicyThings?folderId=

I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37