For Loop in Python 3.0 [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So, I have a really weird question that has kinda always bugged me. In this example:
patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'
for pattern in patterns:
print('Looking for "%s" in "%s" ->' % (pattern, text))
So this is just a example, but what I'm wondering, is in the for loop, pattern was never declared, and I know that Python is a dynamic language so you dont have to declare variables, but how does python like know what it means? I've seen this alot with for loops and alot of the time it just seems like people put whatever they want in that part of the for loop, and I really don't get it. Does it matter what you put there?

With for loops, you're iterating over what is in patterns. What it will do is assign the first object in the list patterns to the variable pattern. And then do it again with the next object.
If you run that code, you get the following output:
Looking for this in Does this text match the pattern?
Looking for that in Does this text match the pattern?
^
|
The arrow points to the variable pattern, which changes every time the loop restarts. I should also point out that this is how the for loop runs in basically every language, including C, Java and Python.
Another simple example to demonstrate this would be to iterate over a python list of integers, done through the range() function:
for i in range(5): # range creates this: [0, 1, 2, 3, 4]
print(i)
Output:
0
1
2
3
4

Related

Finding a combination of characters and digits in a string python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I have a list of lists, and I'm attempting to loop through and check to see if the strings in a specific index in each of the inner lists contain a combination of "XY" and then 4 numbers immediately following. The "XY" could be in various locations of the string, so I'm struggling with the syntax beyond just using "XY" in row[5]. How to I add the digits after the "XY" to check? Something that combines the "XY" and isdigit()? Am I stuck using the find function to return an index and then going from there?
You can use Python's regex module re with this pattern that matches XY and then four digits anywhere in the string.
import re
pattern = r'XY\d{4}'
my_list = [['XY0'],['XY1234','AB1234'],['XY1234','ABC123XY5678DEF6789']]
elem_to_check = 1
for row in my_list:
if len(row) > elem_to_check:
for found in re.findall(pattern, row[elem_to_check]):
print(f'{found} found in {row[elem_to_check]}')
Output:
XY5678 found in ABC123XY5678DEF6789

Can I slice a sentence while ignoring whitespaces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Like the title says, can I slice a sentence while ignoring whitespaces in Python?
For example, if the last letter of my word is sliced, the second letter of the following word needs to be sliced (while I'm using [::2]). I also have to preserve punctuations, so split isn't really an option. Replacing whitespaces isn't an option either, because I would have no way to put them back in the correct spot.
Sample input:
Myevmyozrtilets gwaaarkmv yuozub ubpi farfokm ctbhpe pientsfiydqe. zBmuvtk tahgelyu anlpsmo ttzevagrk yioquj awpyaoryts.
Expected output:
Memories warm you up from the inside. But they also tear you apart.
Sample implementation below.
Takes in consideration the punctuation (it looks like you've got it apart of the whitespace).
You'd enjoy trying to implement it on your own, I'm sure.
f="Myevmyozrtilets gwaaarkmv yuozub ubpi farfokm ctbhpe pientsfiydqe. zBmuvtk tahgelyu anlpsmo ttzevagrk yioquj awpyaoryts."
def g(f):
c=0
for l in f:
if l not in string.ascii_letters:
yield l
else:
if c%2==0:
yield l
c+=1
''.join(g(f))
'Memories warm you up from the inside. But they also tear you apart.'

How to selectively replace characters in a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
How would I replace characters in a string for certain indices in Python?
For example, I have version = "00.00.00" and need to change each of the 0s to a different value, say 3, to look like "33.33.33". Also, would this be possible if I had a variable storing this value. If I have vnumber = "3", would I be able to get the same output by using the variable? I'm sure replace() is a good function to use for this, but I'm not sure about syntax.
From an interactive session, you could type:
>>> help(str.replace)
But to answer the question most directly:
vnumber = '3'
newversion = version.replace('0', vnumber)
Is probably what you want to do.
Your guess about str.replace was right. It takes to arguments, the first is the string to be found in the original string, and the second is the string to replace the found occurrences of the first argument with. Code could be like this:
vnumber = "3"
version = "00.00.00"
newversion = version.replace("0", vnumber)
print(newversion)

Can someone please explain how loop will work? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
for x in s[:].split():
s = s.replace(x, x.capitalize())
I want to know how the for loop will progress and what exactly s[:] means and will do?
Assuming s is a string, s[:] makes a copy of the string, and split() splits the string at spaces and returns an array of substrings, the for loop will then iterate over the substrings.
It's actually unnecessary because split returns an array, so even the though the for loop modifies the original string, the loop iterable isn't reevaluated multiple times, so you don't need to copy it.
s is very likely to be a string because the split is a method in str (of course, you can also say that s is an instance, which comes from a class that is defined by the user in which also has a split method ...)
Normally s[:] is like a slice. The following can help you to understand.
s ='abc AB C dd'
print(s)
print(s[:]) # same as s
print(s[:3]) # abc
print(s[4:6]) # AB
print(s[-1]) # d
for x in s[:].split():
s = s.replace(x, x.capitalize())
print(s) # Abc Ab C Dd # Now you know the capitalize is what, right?
digression
The following is a digression.
I think your question is very bad,
First, this question is very basic.
second, its subject is not good.
Note that an ideal Stack Overflow question is specific and narrow -- the idea is to be a huge FAQ.
And now, you tell me searching how the loop will work? I mean, if you are a programmer who must know how the loop it is.
so when you ask a question, you have to think twice about what the title name can benefit everyone. (not just you only)
I suggest that you can delete this question after you understand it.

Test case in python like C programming language [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I write following while loop in python?
int v,t;
while (scanf("%d %d",&v,&t)==2)
{
//body
}
Python being a higher level language than C will normally use different patterns for this kind of situation. There is a deleted question that in fact had the exact same behavior than your C snippet - and thus would be "correct", but it became so ugly a piece of code in Python it was downvoted pretty fast.
So, first things first - it is 2015, and people can't simply look at a C's "scanf" on the prompt and divine they should type two white space separated integer numbers - you'd better give then a message. Anther big difference is that in Python variable assignments are considered statements, and can't be done inside an expression (the while expression in this case). So you have to have a while expression that is always true, and decide whether to break later.
Thus you can go with a pattern like this.
while True:
values = input("Type your values separated by space, any other thing to exit:").split()
try:
v = int(values[0])
t = int(values[1])
except IndexError, ValueError:
break
<body>
This replaces the behavior of your code:
import re
while True:
m = re.match("(\d) (\d)", input()):
if m is None: #The input did not match
break #replace it with an error message and continue to let the user try again
u, v = [int(e) for e in m.groups()]
pass #body

Categories

Resources