简体   繁体   English

在 Python 中的字符串中获取另一个字符之前的字符

[英]Get the character before another in a string in Python

The thing I am trying to achieve is that I want to get the character before another one in a string.我想要实现的事情是我想在字符串中的另一个字符之前获取字符。 For eg, if the string is "a0c1e2g3", I want to get what's written in the index[0] by just having the index[1] like i want to get the value of the index[0] ("a") when I only have the value of index[1] ("1").例如,如果字符串是“a0c1e2g3”,我想通过索引[1]来获取索引[0]中写入的内容,就像我想获取索引[0](“a”)的值一样我只有 index[1] ("1") 的值。 I want it for all characters.我希望它适用于所有角色。 I want the string to be extendable too.我也希望字符串是可扩展的。

Expected result:预期结果:

a
c
e
g

The result I could get till:我可以得到的结果:

0
2
4
6

The code I tried:我试过的代码:

s = "a0c1e2g3"
for c, i in enumerate(s):
    if i.isdigit():
        alpha_before_int = c-1
        print(alpha_before_int)
        # I want to get "a", "c", "e", "g"
>>> s = "a0c1e2g3"
>>> for c, i in enumerate(s):
...     if i.isdigit():
...         alpha_before_int = s[c-1]
...         print(alpha_before_int)
...         # I want to get "a", "c", "e", "g"
... 
a
c
e
g
>>> 

You can use zip :您可以使用zip

[c for c, n in zip(s, s[1:]) if n.isdigit()]

Or using re :或使用re

re.findall('(.)\d', s)

['a', 'c', 'e', 'g']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM