如何在Python中从第一个数字开始拆分字符串

huangapple go评论58阅读模式
英文:

How to split a string starting from first digit in python

问题

我正在寻找一个Python内置函数,可以帮助我从数字开始的地方拆分字符串。
例如:

输入:TengGigE0/0/3/4
输出:0/0/3/4

输入:TengigabitEthernet 4/3/4/3
输出:4/3/4/3

输入:Te0/4/5
输出:0/4/5

如果不使用正则表达式,如何在Python中实现这个目标?

英文:

I'm looking for a python built-in function that will help me to split a string starting from where a digit starts.
For example

input: TengGigE0/0/3/4 
output: 0/0/3/4

input TengigabitEthernet 4/3/4/3
output: 4/3/4/3

input: Te0/4/5 
output: 0/4/5 

How can this be achieved in python, if not in regex ?

答案1

得分: 0

你可以遍历字符串,并在遇到数字的索引处进行拆分。

s = 'TengGigE0/0/3/4'

from string import digits

for char in range(len(s)):
    if s[char] in digits:
        print(s[char:])
        break

输出结果:

0/0/3/4
英文:

You can traverse the string and split on the index where you encounter a digit.

s = 'TengGigE0/0/3/4'

from string import digits

for char in range(len(s)):
	if s[char] in digits:
		print(s[char:])
		break

Output:

0/0/3/4

答案2

得分: 0

如果考虑内置模块 [`re`](https://docs.python.org/3/library/re.html)您可以从第一个数字提取到末尾

```python
import re

m = re.search(r'\d.*', 'TengGigE0/0/3/4')
out = m.group()

正则表达式演示

或者,移除所有前导非数字字符:

import re

out = re.sub(r'^\D+', '', 'TengGigE0/0/3/4')

正则表达式演示

输出: '0/0/3/4'

另一种方法是使用内置的 itertools.dropwhile

from itertools import dropwhile

out = ''.join(dropwhile(lambda x: not x.isdigit(), 'TengGigE0/0/3/4'))

其他输出:

# TengigabitEthernet 4/3/4/3
4/3/4/3

# Te0/4/5
0/4/5

<details>
<summary>英文:</summary>

If you consider the builtin module [`re`](https://docs.python.org/3/library/re.html), you could extract from the first digit to the end:

import re

m = re.search(r'\d.*', 'TengGigE0/0/3/4')
out = m.group()

[regex demo](https://regex101.com/r/8ucuXY/1)

Or, removing all the leading non-digits:

import re

out = re.sub(r'^\D+', '', 'TengGigE0/0/3/4')

[regex demo](https://regex101.com/r/Dy2ikv/1)

Output: `&#39;0/0/3/4&#39;`

Another approach with the builtin [`itertools.dropwhile`](https://docs.python.org/3/library/itertools.html#itertools.dropwhile):

from itertools import dropwhile

out = ''.join(dropwhile(lambda x: not x.isdigit(), 'TengGigE0/0/3/4'))


Other outputs:

TengigabitEthernet 4/3/4/3

4/3/4/3

Te0/4/5

0/4/5


</details>



huangapple
  • 本文由 发表于 2023年7月20日 16:28:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定