3

I'm trying to separate characters from any given strings and making subsring with it. For example,

str='abcd' => 'ab','bc','cd'

Here is my solution,

str='abcdef'
a=[]
for i in range(len(str)):
  a.append(str[i:i+2])
a.remove(a[-1])
print(a)

This works but I would like to know better way to do it.

Thanks

4
  • 1
    What is the logic? Do you want all the substrings of length 2? Commented Apr 27, 2019 at 16:40
  • Yes, as I showed the output should be: ab, bc, cd, de, ef Commented Apr 27, 2019 at 16:41
  • [str[p:p+2] for p in range(len(str)-1)] Commented Apr 27, 2019 at 16:43
  • 1
    Unrelated, but str is a builtin function. Do not use it as a variable. Commented Apr 27, 2019 at 16:43

2 Answers 2

5

A possible solution without external modules (like your implementation, but cleaner).

[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']
Sign up to request clarification or add additional context in comments.

Comments

5

Use zip() (Built-in):

[f'{x}{y}' for x, y in zip(s, s[1:])]

Code:

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.