#🔒 String methods

128 messages · Page 1 of 1 (latest)

smoky musk
#

Let’s say I wanted to change every ‘1e’ to first for example without using any lists or anything, how can I make a condition if the next element after 1 is e?

queen palmBOT
#

@smoky musk

Python help channel opened

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.

winter jasper
#

You something like

smoky musk
#

This is what I did, but what if lists cant be used

real shard
#

Well, in some way you need to dissect your string.

#

You could use a regexp I suppose.

winter jasper
#

!e ```py
string = "Hel1lo"
print(string.replace("1", "1e"))

queen palmBOT
smoky musk
#

I have never heard of regexp, we haven’t really used that

#

oh forgot to mention, you can’t use the replace function

real shard
smoky musk
#

Just an exercise and usually exams are like that here too

ashen kindle
#

als je er niet uitkomt kan je gewoon de vraag aan bing copilot stellen

#

dan krijg je werkende code

real shard
#

In only because replace doesn't have a way to recognise words.

ashen kindle
#

Sorry

smoky musk
real shard
#

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.

ashen kindle
#
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

real shard
#

Of course, re.sub is morally a lot like using str.replace 🙂

smoky musk
#

But if there are multiple 1e’s how would it do it?

real shard
#

With a loop. Repeat until str.find does not find a 1e.

ashen kindle
#

you could also iterate over the strings and check using list indexes

real shard
#

Or a loop to scan along the original unchanged string, assembling the modified string as you go.

smoky musk
#

so while str.find(‘1e’)!=-1

#

Basically

real shard
#

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.

smoky musk
#

Hmm

ashen kindle
#
final = ""
chunks = text.split('1e')
for chunk in chunks:
  final += "first" + chunk
text = final
print(text)
#

is also a solution

real shard
#

... does not detect word boundaries. But yet, a starting point for a solution.

ashen kindle
#

!ex

real shard
#

Nothing wrong with trying.

smoky musk
#

But sometimes there are restrictions on the exercise

#

and I prob can’t use lists

#

but anyways

real shard
#

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.

ashen kindle
#

Be careful not to go out of bounds tho?

real shard
#

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).

smoky musk
#

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

real shard
#

... you then do another scan from offset_of_1e+2 onward.

#

Thus the need for a loop.

smoky musk
ashen kindle
#

'alabama1eakjakshakj1esdsakjhdaksjd1eaakkjjka'.split("1e").join("first")

#

wouldn't that work

real shard
#

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

ashen kindle
#

works

real shard
#

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.

smoky musk
#

I do not understand the logic of the last line

#

len(‘eerste’)+offset_after_1e

real shard
#

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.

smoky musk
#

I see

#

Makes sense

smoky musk
real shard
#

'1e' is the string you're looking for, offset is where you are starting to look.

smoky musk
#

ah

real shard
smoky musk
#

Why do I need to still look at the spaces

#

Doesn’t the s= … deal with that

real shard
#

Well you wants only the word 1e, not eg foo1ebah yes?

smoky musk
#

yeah correct

real shard
#

.find just looks for the string. Doesn't care about notions like words.

smoky musk
#

I mean 1e in our language can’t be in that

real shard
#

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".

pastel cave
#

change 1e to first
no lists, not .replace(and re equivalences)
no .replace I can get behind, why no lists? also a restriction of the exercise?

real shard
#

So .find is just a dumb "find these characters in sequence, anywhere".

smoky musk
real shard
#

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.

smoky musk
real shard
#

A lot of real world programming is "here's some problem, here's a library or API etc", solve the problem using it.

pastel cave
real shard
#

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.

pastel cave
#

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'
real shard
#

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.

smoky musk
real shard
#

That's ok.

real shard
#

Some methods are simply "here's a reasonable thing to do with a string". Which ones you use depend on the task.

real shard
#

It's an acquired skill, alas. But you know the task. See which methods fit parts of the task.

smoky musk
#

It looks at element per element

real shard
#

There's a .startswith method too.

#

See its docs.

smoky musk
pastel cave
smoky musk
#

and why can’t you add 1e if its at the beginning?

smoky musk
#

so basically if s[i] = 1 and s[i+1] = e

#

you want to change it to eerste

pastel cave
#

also see how I use a while loop instead of a for
it allows you to control how i increments

smoky musk
#

yeah that actually makes sense

#

else you just add the elements

pastel cave
#

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

smoky musk
#

Is join here needed?

#

prob not because you keep adding the elements

real shard
#

Yeah. Incrementally building a string with += is quite expensive. If you've got a list (forbidden!) then the .join method is very efficient.

pastel cave
smoky musk
#

Yeah exactly

#

Well the method with lists was far better, but ofc restrictions

#

Thanks everyone!

#

I’ll have my exam soon, appreciate the help

queen palmBOT
#
Python help channel closed

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.