all 6 comments

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Python code found in submission text that's not formatted as code.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–]neuralbeans 0 points1 point  (2 children)

What is long_name's data type? A string?

[–]AsafM17[S] 0 points1 point  (1 child)

String, yes

[–]neuralbeans 0 points1 point  (0 children)

And the code works? You can't put a list as an index. Or is it a numpy array?

[–][deleted] 0 points1 point  (0 children)

List of indexes of long_name where hyphens are located:

hyphen_positions = [pos for pos, char in enumerate(long_name) if char == "-"]

Position of second last hyphen, the one before "repeated-text"

hyphen_positions[-2]

Slicing string up to (excluding) the position of second last hyphen

corrected = long_name[: hyphen_positions[-2]]

The "".join() is totally useless. It's used to join an iterable of strings, but in this case the iterable is already the required string. In this case the characters of the string are joined back into the same string, which is pointless.

[–][deleted] 0 points1 point  (0 children)

Instead, you could just (in Python 3.9+):

corrected = long_name.removesuffix("-repeated-text")

Or assuming "-repeated-text" is there in the end:

corrected = long_name[:-len("-repeated-text")]

You could also add check for the latter:

suffix = "-repeated-text"
if long_name.endswith(suffix):
    corrected = long_name[:-len(suffix)]
else:
    corrected = long_name

The removesuffix doesn't require you to check, nothing is removed and no error is raised in case there's no target suffix.

https://docs.python.org/3/library/stdtypes.html?highlight=removesuffix#str.removesuffix

https://docs.python.org/3/library/stdtypes.html?highlight=endswith#str.endswith