我想从任意给定的字符串中分离字符并创建子字符串。例如,
str='abcd' => 'ab','bc','cd'
这是我的解决方案,
str='abcdef'
a=[]
for i in range(len(str)):
a.append(str[i:i+2])
a.remove(a[-1])
print(a)
这个可以运行,但我想知道更好的做法。谢谢。
我想从任意给定的字符串中分离字符并创建子字符串。例如,
str='abcd' => 'ab','bc','cd'
这是我的解决方案,
str='abcdef'
a=[]
for i in range(len(str)):
a.append(str[i:i+2])
a.remove(a[-1])
print(a)
[my_str[i:i+2] for i in range(len(my_str) - 1)]
so
In [3]: my_str='abcdef'
In [4]: [my_str[i:i+2] for i in range(len(my_str) - 1)]
Out[4]: ['ab', 'bc', 'cd', 'de', 'ef']
使用内置函数 zip()
:
[f'{x}{y}' for x, y in zip(s, s[1:])]
代码:
s = 'abcdef'
print([f'{x}{y}' for x, y in zip(s, s[1:])]) # Python 3.6+. For previous versions, use below line.
# [x + y for x, y in zip(s, s[1:])]
# Outputs: ['ab', 'bc', 'cd', 'de', 'ef']
[str[p:p+2] for p in range(len(str)-1)]
- 101arrowzstr
是一个内置函数。不要将其用作变量。 - Valentino