Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Increment two strings at the same time

I want to be able to interate both list1 = list('asdf') and list2 = list('qwer') at the same time. What is the best approach?

for i, p in list1, list2:
    print(i,p)

Where i would be increment list1 and p would be increment list2.

like image 662
IntriquedMan Avatar asked Aug 29 '12 21:08

IntriquedMan


People also ask

How do you increment two variables in Python?

Yes, the += operator allows adding more than just a single value at a time. Anything on the right-hand side of the += will be evaluated, and then it will be added to the variable which is then updated to that new value.

Can you increment strings in Python?

Because strings, like integers, are immutable in Python, we can use the augmented assignment operator to increment them.

How do you increment a character in a string in python?

To increment a character in a Python, we have to convert it into an integer and add 1 to it and then cast the resultant integer to char. We can achieve this using the builtin methods ord and chr.

How do you shuffle two strings in python?

It works by getting the first character of each string and recursively shuffling the rest and adding this character to each element in the list. When there is one character remaining on each of the strings it returns a list where the character is added in each position of the other string.


1 Answers

Use zip (or itertools.izip if the two lists are large):

for i, p in zip(list1, list2):
    print(i, p)

Alternately, if list1 might not be the same length as list2 use izip_longest from itertools

like image 125
Sean Vieira Avatar answered Sep 22 '22 19:09

Sean Vieira