How to properly iterate through a for loop with python - python

I am relatively inexperienced and come from c#. I am attempting to iterate through a string and individually print out each letter using a for loop.
In c# this would (if I remember correctly) be written like so:
string x = test;
foreach(i in x)
{
print(x[i]);
}
But in python, when I type
x = "test"
for i in x:
print(x[i])
The python shell tells me that i must be an integer.
I am actually pretty sure that my syntax is incorrect in my c# example, but to get to the question:
How would i properly iterate through a string using a for, or foreach loop in Python?
I have been searching the web and am somehow coming up empty handed. Sorry if this is a foolish inquiry.

Your variable x is a string type, therefore, when you type x[i] you are going to get the letter at the position i.
However, in your loop, you have something different:
x = "test"
for i in x:
print(x[i])
This for loop (for i in x) means: for each letter i in the string x, do the following. So, your i variable is actually a letter, not an integer.
So, to print every letter of the string x, just use print(i):
x = "test"
for i in x:
print(i)
But, if you really want your i to be an integer, instead of for i in x, use for i in range(0, len(x)). And in this case, you would have to access the letter by using what you originally wrote (x[i]).
x = "test"
for i in range(0, len(x)):
print(x[i])

If you really want a loop index for some reason, you can use enumerate:
x = 'test'
for i, c in enumerate(x):
print(i, x[i], c)

This took me a bit to understand as well, but I think I understand the misunderstanding. The i in for i in x already refers to the character, not the index. For example, writing
stringx='hello world
for i in stringx:
print stringx[i]
is the same as writing
print stringx['h']

Related

Delete elements of a List, using a condition

Hello I'm learning to program in Python to manipulate data bases and I can't make this simple task. Please someone help me.
I have this list
CIS=['4998200lp','2159140lp','02546or']
I want to get this result:
CIS=['4998200lp','2159140lp','2546or']
I was trying something like:
for x in CIS:
izq= x[:1]
if izq == 0:
CIS=[x.replace(x[:1],'') for x in CIS]
print (CIS)
I just want to delete the first element of every string for the condition izq == 0.
Your description doesn't match your example input/output which also differs from your code.
Based on the example input/output, I suspect what you're trying to do is strip a single leading 0 from any string that starts with 0. And that's not too bad, but you can't do it in a for loop without having an index to assign back to. For that, you can use enumerate:
for i, x in enumerate(CIS):
if x.startswith('0'): # or x[:1] == '0' if you really prefer
CIS[i] = x[1:]
Alternatively, you can use a list comprehension to replace CIS:
CIS = [x[1:] if x.startswith('0') else x for x in CIS]
and to mutate in place (rather than making a new list), use the same comprehension but assign to the full slice, which makes it behave like the spelled out loop in the first example:
CIS[:] = [x[1:] if x.startswith('0') else x for x in CIS]
The difference between examples #1/#3 and example #2 occurs if CIS was passed as an argument to a function, or otherwise is referenced in multiple places. In #1/#3, it's mutating the list in place, so all references will see the updates, in #2, it's reassigning CIS, but leaving the original list unchanged; if other references exist, they won't appear changed.
Note: If the goal is to remove all leading 0s, then use str.lstrip, e.g.:
CIS = [x.lstrip('0') for x in CIS]
with similar adaptations for the other approaches. You don't even need to test for the presence of 0 in that case, as lstrip will return the str unmodified if it doesn't begin with 0.
If you are simply looking to remove the first zero of every string, utilize the startswith method. Also, don't look for an integer 0. Look for a string '0'.
Finally, you can simplify your implementation with doing this all in a comprehension, creating a new list with your new data:
[w[1:] if w.startswith('0') else w for w in CIS]
Outputs:
['4998200lp', '2159140lp', '2546or']
Just try to delete first character of every elements that starts with 0:
CIS=['4998200lp','2159140lp','02546or']
for i,v in enumerate(CIS):
if v.startswith('0'):
CIS[i] = v[1:]
CIS # ['4998200lp', '2159140lp', '2546or']
Actually your loop contained a very close approach to a working solution:
CIS=['4998200lp','2159140lp','02546or']
CIS=[x.replace(x[:1],'') for x in CIS]
but this would strip all first elements. To only replace them if they are '0' (notice that's not the same as the integer: 0) you need to incorporate you if ... else ... into the list-comprehension:
CIS=['4998200lp','2159140lp','02546or']
CIS=[x.replace(x[:1],'',1) if x[:1] == '0' else x for x in CIS ]
The if ... else ... syntax might be a bit strange but just try to read the code aloud: "Insert the replaced x if the first character is a zero or if not insert x, for every x in CIS".
The other answers contain much more sophisticated approaches but I just wanted to add this answer to give you a heads-up that you were on the right track!
But it's generally a bad idea to use a list-comprehension inside a for loop if they iterate over the same iterable. Mostly you just want one of them.

How to delete the very last character from every string in a list of strings

I have the strings '80010', '80030', '80050' in a list, as in
test = ['80010','80030','80050']
How can I delete the very last character (in this case the very last digit of each string which is a 0), so that I can end up with another list containing only the first four digits/characters from each string? So end up with something like
newtest = ['8001', '8003', '8005']
I am very new to Python but I have tried with if-else statements, appending, using indexing [:-1], etc. but nothing seems to work unless I end up deleting all my other zeros. Thank you so much!
test = ["80010","80030","80050"]
newtest = [x[:-1] for x in test]
New test will contain the result ["8001","8003","8005"].
[x[:-1] for x in test] creates a new list (using list comprehension) by looping over each item in test and putting a modified version into newtest. The x[:-1] means to take everything in the string value x up to but not including the last element.
You are not so far off. Using the slice notation [:-1] is the right approach. Just combine it with a list comprehension:
>>> test = ['80010','80030','80050']
>>> [x[:-1] for x in test]
['8001', '8003', '8005']
somestring[:-1] gives you everything from the character at position 0 (inclusive) to the last character (exclusive).
Just to show a slightly different solution than comprehension, Given that other answers already explained slicing, I just go through at the method.
With the map function.
test = ['80010','80030','80050']
print map(lambda x: x[:-1],test)
# ['8001', '8003', '8005']
For more information about this solution, please read the brief explanation I did in another similar question.
Convert a list into a sequence of string triples
In python #Matthew solution is perfect. But if indeed you are a beginer in coding in general, I must recommend this, less elegant for sure but the only way in many other scenario :
#variables declaration
test = ['80010','80030','80050']
length = len(test) # for reading and writing sakes, len(A): length of A
newtest = [None] * length # newtest = [none, none, none], go look up empty array creation
strLen = 0 # temporary storage
#adding in newtest every element of test but spliced
for i in range(0, lenght): # for loop
str = test[i] # get n th element of test
strLen = len (str) # for reading sake, the lenght of string that will be spliced
newtest[i] = str[0:strLen - 1] # n th element of newtest is the spliced n th element from test
#show the results
print (newtest) # ['8001','8003','8005']
ps : this scripts, albeit not being the best, works in python ! Good luck to any programmer newcommer.
I had a similar problem and here is the solution.
List<String> timeInDays = new ArrayList<>();
timeInDays.add(2d);
timeInDays.add(3d);
timeInDays.add(4d);
I need to remove last letter in every string in-order to compare them. Below solution worked for me.
List<String> trimmedList = new ArrayList<>;
for(int i=0;i<timeInDays.size();i++)
{
String trimmedString = timeInDays.get(i).substring(0,name.length()-1);
trimmedList=add(trimmedString );
}
System.out.println("List after trimming every string is "+trimmedList);

Replacing Odd and Even-indexed characters in a string

How can I replace even and odd-indexed letters in my strings? I'd like to replace odd-indexed characters with uppercased letters and even-indexed characters with lowercased ones.
x=input("Enter String: ")
How can I modify the inputted string?
This sounds a little like a "do my homework for me" post, but I'll help you out, as I need the training myself.
You can do this by breaking down the problem. (As I am quite new with python syntax, I'm gonna assume that the user has already given an input to string x)
Make a loop, or otherwise iterate through the characters of your string
Make sure you have an index number for each character, which increments for each one
Check if the number is even, by using modulus of 2 (%2). This returns the remainder of a number when divided by 2. In the case of even numbers, that will be 0.
If %2 == 0 set letter to lower case, else set letter to upper case.
append letter to new String, which you defined before the loop. You cannot directly alter a single character in a String, because they are immutable. This means that you cannot change the String itself, but you can assign a new String to the variable.
Done. Print and see if it worked.
Code:
x = "seMi Long StRing WiTH COMPLetely RaNDOM CasINg"
result_string = ""
index = 0;
for c in x:
if(index%2 == 0):
result_string += c.lower()
else:
result_string += c.upper()
index+=1
print(result_string)
s=input()
l=[]
s=s.lower()
l=[i.upper() if s.index(i)%2==0 else i for i in s ]
print("".join(l))
x = 'myname'
for item in range(len(x)):
if item%2==0:
print(x[item].upper())
else:
print(x[item].lower())
this is the for loop i was referring to. but the thing with this line of code is that it is specific to the value you have assigned to the variable x where as the function i provided above can take any string value without us having to repeat the code each time.
def myfunc(string):
result=''
for x in range(len(string)):
if x%2==0:
result=result+string[x].upper()
else:
result=result+string[x].lower()
return result
The above is a function for the question you asked.
A non-function for loop might be easier to grasp right now (like you I am very new to Python as well. So for me it was easier to understand the for loop before I got into functions. Look at my next post for the same.

python small crosswords for beginners

my_str="ellezagchickenbndodetballigatoraaaolmeznacattleeblrctacfenarcesssadlritfhftrarrssos aoiarefaareppohssarghcerumrheirmmwildfcumeboimltaairfovindalbiglalobehoeasiaxuesabldinbbccrhhrtylrlahsifdlogkrctlaiareogoldfinchefnnddmneepoletnarntadodinosauroxofoeclictnahpelepalgaierhohcaorkcocyatrmoacrflamingoerefafloechateehchdracaribou"
def create_2d_list(N):
output_list=[]
counter=0
for row in range(0,N):
temp=[]
for col in range(0,N):
temp.append(my_str[counter])#you can add a charcter instead of counter
counter=counter+1
output_list.append(temp[:])
return output_list
N=18
x=create_2d_list(N)
for row in range(0,N):
total=0
s="|"
for col in range(0,N):
my_str="{0:2} ".format(x[row][col])
s=s+my_str+"|"
print "-"*(N*4+1)
print s,
print " "
the_valid_words=open("E:/asd/words.txt","r").readlines()
def looking_word_left_to_right(the_list):
for any_words in the_valid_words:
for every in x[0]:
the_first_index=x[0].index(every)
for every in range(the_first_index,(the_first_index)+7):
c=str(every)
the_join=" ".join(c)
if the_join==the_valid_words:
word.upper().replace(every,x[0].upper(every))
return x[0]
print looking_word_left_to_right(x)
every time i run the program, the looking_word_left_to_right doesn't print anything
P.S its similar to small crossword for beginners, Capitalizing the letters that make a word and removing every other letter without changing places, if someone could give like thoughts on how to proceed that would be great. i have certain valid words to look for.
and i'm a newbie so go easy on me :)
appreciate the help.
There seem to be a number of problems.
Why are you operating on x when you also pass it in as the_list" Just use the_list.
You're only looking at the first line of x and never moving beyond that.
It looks like you're putting a space between every character before you compare. If c = "abcdefg" then " ".join(c) will give you "a b c d e f g". If your the_valid_words doesn't have spaces in it, then if the_join==the_valid_words will always evaluate to false.
You're comparing to the_valid_words, which is your entire list. You should probably be comparing to EACH valid word using any_word... which you aren't using anywhere else.
You may also be running into a problem with iterating over x, while you're changing it (it will sometimes invalidate the iterator... but sometimes not). I.e. if you're iterating through x and then you change x before you're done iterating, then Python might not know where the iterator belongs in the new version of x. Since the_list is the same as x anyway, it might be better to do for every in the_list: and then change x to your heart's content.
It looks like you may not quite understand how for loops work in Python. Take a look at those, and that may help some.

Read two variables in a single line with Python [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 20 days ago.
I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?
I'm looking for the equivalent of:
scanf("%d%d", &i, &j); // accepts "10 20\n"
One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way?
This is not for live use. Just for learning..
No, the usual way is raw_input().split()
In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings
Don't use input() for that. Consider what happens if the user enters
import os;os.system('do something bad')
You can also read from sys.stdin
import sys
a,b = map(int,sys.stdin.readline().split())
I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:
i,j = raw_input("Enter two values: ").split()
i = int(i)
j = int(j)
Granted, the code is not as elegant as the one-liners using C's scanf or C++'s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.
In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .
In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. str values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python's built-in int or float function.
I know this posting is a reply to a very old posting and probably the knowledge has been out there as "common knowledge" for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.
Firstly read the complete line into a string like
string = raw_input()
Then use a for loop like this
prev = 0
lst = []
index = 0
for letter in string :
if item == ' ' or item == '\n' :
lst.append(int(string[prev:index])
prev = index + 1
This loop takes a full line as input to the string and processes the parts in it individually and then appends the numbers to the list - lst after converting them to integers .
you can read 2 int values by using this in python 3.6.1
n,m = map(int,input().strip().split(" "))
You can also use this method for any number of inputs. Consider the following for three inputs separated by whitespace:
import sys
S = sys.stdin.read()
S = S.split()
S = [int(i) for i in S]
l = S[0]
r = S[1]
k = S[2]
or you can do this
input_user=map(int,raw_input().strip().split(" "))
You can use this method for taking inputs in one line
a, b = map(int,input().split())
Keep in mind you can any number of variables in the LHS of this statement.
To take the inputs as string, use str instead of int
And to take list as input
a = list(map(int,input.split()))
in python 3.9 , use a, b = map(int,input().split())
because you will get raw_input() not defined

Categories