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

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.

Related

why the output of this code is the same in the array? [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.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I saw this code on YouTube. The code should turn all lower case strings (ab ,cd) into upper case string but when I tried this code the output was the same as the array without change. I want know what is going on behind the scenes.
x = ['ab', 'cd']
for i in x:
i.upper()
print(i)
upper() returns the uppercase of the string it's called on, but does not modify that string. So you're calling upper(), but then ignoring its return value.
You could capture the return value in a variable and then print it:
for i in x:
u = i.upper()
print(u)
Or just print it directly:
for i in x:
print(i.upper())
Here. I hope this works!
x = ['ab', 'cd'] # Your array
uppercase_string = str(x).upper() # makes uppercase
print(uppercase_string) # prints uppercase
You don't need to make a for loop to
print an array. Plus posting an image makes it harder for answers to be made.
You can put print(i.upper()) instead of just print.
That didn't work because, i.upper() returns the string back after converting all the letters to uppercase, thus you can either use an assignment statement to keep hold of it or print it out like the one mentioned above.

Can someone explain how the indexing on strings work with 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 1 year ago.
Improve this question
Given
a = "helloworld"
print(a[0][0][0][0])
When I run this program, it gave me "h" as output. Can someone explain how this works??
[0] always gets the first character, because it is the first index of the string (or list)
So, if you do print(a[0]), it would give the first character 'h'
If you add [0] to it, it would give the first character of 'h' which is 'h' itself
So, if you keep adding the [0], it would still give you 'h'
In every languages when it comes to an array it means you are considering a sequence of data's all together of same dataType in a such a manner that the first element is always present at index 0 and the last element is present at the (size of the array provided by the programmer) -1, basically it is a data structure that is used to store values of homogeneous type.

Most Pythonic way to extract a number from 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 2 years ago.
Improve this question
I have a string containing a number, starting with x, for example, "x270" or "x9". It always starts with x. I need to get the number.
I'm doing this:
blatz = "x22"
a1 = int(re.search("x(\d+)", blatz).group(1))
This doesn't seem very Pythonic. I would welcome more elegant solutions.
Using re library seems to be an overkill. You don't have to search for a pattern, because you're saying that each string starts with x.
So you simply can do slicing:
blatz = "x22"
a1 = int(blatz[1:])
If you need further checks, you can look at str.startswith(), str.endswith and/or str.isdigit().
While slicing looks very pythonistic, there is also the possibility to use other string methods that lead to the same goal:
blatz = "x22"
a2 = int(blatz.lstrip("x")) # strip "x" from the left
a3 = int(blatz.partition("x")[-1]) # get everything after "x"
a4 = int(blatz.replace("x", "")) # replace every "x" with empty string
...
But slicing is faster and nothing unusual for Python programmers.
Please check out this.
import re
blatz = "x22"
print(re.search("\d", blatz).group())

Search and Replace a word within a word in Python. Replace() method not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How do I search and replace using built-in Python methods?
For instance, with a string of appleorangegrapes (yes all of them joined),
Replace "apple" with "mango".
The .replace method only works if the words are evenly spaced out but not if they are combined as one. Is there a way around this?
I searched the web but again the .replace method only gives me an example if they are spaced out.
Thank you for looking at the problem!
This works exactly as expected and advertised. Have a look:
s = 'appleorangegrapes'
print(s) # -> appleorangegrapes
s = s.replace('apple', 'mango')
print(s) # -> mangoorangegrapes
The only thing that you have to be careful of is that replace is not an in-place operator and as such it does not update s automatically; it only creates a new string that you have to assign to something.
s = 'appleorangegrapes'
s.replace('apple', 'mango') # the change is made but not saved
print(s) # -> appleorangegrapes
replace can work for any string, why you think that it doesn't, here is the test:
>>> s='appleorangegrapes'
>>> s.replace('apple','mango')
'mangoorangegrapes'
>>>
Don't you see that you received your expected result?

For Loop in Python 3.0 [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 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

Categories

Resources