-2

how can we use for loop to assign two values from the string like following

string="abcd"
for i in string:
      print(i)

this will give i one value from the string

#output
a
b
c
d

how can i take two values like ab and cd. I know we can do this in print but i need to assign two values in "i" I need output

#output
ab
cd

2 Answers 2

3

You could use list-comprehension like the following:

n = 2
s = "abcd"
res = [s[i:i+n] for i in range(0, len(s), n)]
print(res) # ['ab', 'cd']

This is applicable to any nth place.

If its only 2 chars that you are after you can also use regex, but if it for any n its not convenient, an example for n=2 is:

import re
s = "abcd"
res = re.findall('..?',s)
print(res) # ['ab', 'cd']
Sign up to request clarification or add additional context in comments.

1 Comment

@SaadJillani this is a different question, that is unrelated to the one asked here. See this link stackoverflow.com/questions/11476713/… where you will find a way to calculate it without any method used.
0

Try this:

string = "abcd"
for i in range(1,len(string),2):
    print(string[i-1]+string[i])

Output:

ab
cd

Explanation

You can modify the range function to start at index 1 and go all the way through len(string) in steps of 2(range(1,len(string),2))

Then inside the loop, since we start index 1, we print string[i-1] and concatenate with string[i]

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.