#🔒 String methods
128 messages · Page 1 of 1 (latest)
@smoky musk
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
You something like
!e ```py
string = "Hel1lo"
print(string.replace("1", "1e"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Hel1elo
I have never heard of regexp, we haven’t really used that
oh forgot to mention, you can’t use the replace function
Why?
This will turn "11" into "1e1e". The OP's using individual words.
Just an exercise and usually exams are like that here too
als je er niet uitkomt kan je gewoon de vraag aan bing copilot stellen
dan krijg je werkende code
English only please
In only because replace doesn't have a way to recognise words.
Sorry
I do get it, I just want to see any other methods without using lists and replace
What you could do is use str.find to locate the 1e instances, check that they are standalone words by inspecting the text before/after, and then replace. (Not using str.replace.
import re
def replace_1e_with_first(text):
# Define the regex pattern to match "1e"
pattern = r'\b1e\b'
# Replace all occurrences of the pattern with "first"
result = re.sub(pattern, 'first', text)
return result
re is a standard library
Of course, re.sub is morally a lot like using str.replace 🙂
Hmm
But if there are multiple 1e’s how would it do it?
With a loop. Repeat until str.find does not find a 1e.
you could also iterate over the strings and check using list indexes
Or a loop to scan along the original unchanged string, assembling the modified string as you go.
Yes, thought that will be a little less efficient than scanning the original string.
And you have to try a little harder if there's eg a 1e in the replacement string 🙂
You'd be testing s.find('1e'). And find accepts an optional starting point.
Hmm
final = ""
chunks = text.split('1e')
for chunk in chunks:
final += "first" + chunk
text = final
print(text)
is also a solution
... does not detect word boundaries. But yet, a starting point for a solution.
!ex
Nothing wrong with trying.
I already did it with this method
But sometimes there are restrictions on the exercise
and I prob can’t use lists
but anyways
You can assemble a modified string with something like new_s = s[:offset_of_1e] + 'eerste' + s[:offset_of_1e+2], given a suitable offset.
And that 2 can be written len("1e") if you need to be replacing different strings.
Be careful not to go out of bounds tho?
The ranges should be safe with bounds.
An individual index can go out of bounds.
Ugh, the second bit should be offset_of_1e: (colon last - from that offset to the end).
so let’s say I find the ‘1e’ and it gives le some index if index == result then I want to add ‘eerste’ to my sentence
but that’s only for one of the 1e
so if I have multiple ones
I might have to look at something else
I am not sure I am understanding this, sorry…
'alabama1eakjakshakj1esdsakjhdaksjd1eaakkjjka'.split("1e").join("first")
wouldn't that work
some logic like (sketch, untested, incomplete):
offset = 0
offset_of_1e = s.find('1e', offset)
while offset_of_1e >= 0:
# check before and after for spaces
s = s[before the offset] + 'eerste' + s[after the '1e']
offset = offset_of_1e + len('eerste') # start after the replacement
The OP wants 1e as a word on its own.
Needs some extra checking.
They started with a .split(' ') to get words, and are researching other ways of approaching it.
Oh, that loop of mine above needs an additional offset_of_1e = s.find('1e', offset) at the bttom of the loop to do the next search.
It's where in the (modified) string you now need to search from. The start of the old 1e plus the length of eerste which you replaced it with.
Why do you add two arguments here?
'1e' is the string you're looking for, offset is where you are starting to look.
ah
Docs for the .find method: https://docs.python.org/3/library/stdtypes.html#str.find
Thnx.
Why do I need to still look at the spaces
Doesn’t the s= … deal with that
Well you wants only the word 1e, not eg foo1ebah yes?
yeah correct
.find just looks for the string. Doesn't care about notions like words.
I mean 1e in our language can’t be in that
Remember "string methods" is basicly just strings and characters. "words" are a grammatical construct.
And being language specific makes it even harder for it to magicly find only "words".
change
1etofirst
nolists, not.replace(andreequivalences)
no.replaceI can get behind, why nolists? also a restriction of the exercise?
So .find is just a dumb "find these characters in sequence, anywhere".
Yeah I used split, which gives me a list so I can’t sadly
Maybe to make the checking for words more overt?
Maybe to force getting more use of the string methods.
Learning exercises are often like this.
prob yeah
A lot of real world programming is "here's some problem, here's a library or API etc", solve the problem using it.
I'm pretty sure whatever you end up with will have horrible performance
and I wouldn't say this is a good exercise to get you to use str methods anyway
So getting a student to have to use a constrained list of things (a) skips the "oh here's a black box which nearly does the whole thing" and (b) helps learn the "dig through the docs looking for things which can be assembled to make a solution.
imo, the easier solution is to just
new_s = ''
i = 0
while i < len(s):
if 'the substring starting at i is 1e':
'do not add it to new_s'
else:
'add the character to new_s'
Having familiarity with the string methods is good. Having to look at the docs helps with this. And tutorial exercises are always fairly simple. They need to be to put the focus on the task and make the description tractable.
yeah but sometimes I don’t see the logic behind all methods
That's ok.
Hmm
Some methods are simply "here's a reasonable thing to do with a string". Which ones you use depend on the task.
Yup, thats really it
It's an acquired skill, alas. But you know the task. See which methods fit parts of the task.
But how does it know that i is 1e
It looks at element per element
yep
see how I'm deliberately using indices instead of looping over individual characters
that's cause at say i = 5, not only can you look at the 6th character s[i], but also the 7th s[i+1]
and why can’t you add 1e if its at the beginning?
let me see
so basically if s[i] = 1 and s[i+1] = e
you want to change it to eerste
also see how I use a while loop instead of a for
it allows you to control how i increments
do note that for performance, this is really bad; rather than +=-ing to a str, it's way better to use a list, .append stuff to it, then do a ''.join at the end
but for this exercise lists are banned ofc, so you'll have to make do with a str
yeah exactly
Is join here needed?
prob not because you keep adding the elements
Yeah. Incrementally building a string with += is quite expensive. If you've got a list (forbidden!) then the .join method is very efficient.
no, you just work with a string and += to it the entire way
Yeah exactly
Well the method with lists was far better, but ofc restrictions
Thanks everyone!
I’ll have my exam soon, appreciate the help
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.