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
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 n
th 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']
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.