Doubt in String Slicing

Hello Everyone,
I am having a doubt regarding String Slicing, so what I actually need is that for an example if the word “Happy” is the actual content and I need to work with String slicing as that I need to print with required following output as
H y
Ha py
Hap ppy
Happ appy
Happy Happy
so the above results is the required one and I need a simple code to get this to be printed. Can please any one help on this.

By Kaliswaran via Discussions on Python.org at 07Jul2022 09:25:

I am having a doubt regarding String Slicing, so what I actually need
is that for an example if the word “Happy” is the actual content and I
need to work with String slicing as that I need to print with required
following output as
H y
Ha py
Hap ppy
Happ appy
Happy Happy
so the above results is the required one and I need a simple code to
get this to be printed. Can please any one help on this.

Strings are sequences, so you can slice them like any other sequence.
Please read this part of the docs:

where it talks about sequence operations including slicing.

In particular, these idioms apply, if n is a nonnegative integer:

  • s[:n] the first n items of s, so for a string, the first n
    characters
  • s[-n:] the last n items of s, so for a string, the last n
    characters

n is any integer expression, so it could be a variable name etc.

So what you’re asked to do is print the first and last n characters
from a string "Happy", for n from 1 through 5. Most likely, 1
through the length of the string.

I would start by writing a loop to count 1 through to what you need, and
just print the start and end of the string. When that’s correct, then
pursue putting enough space between the two substrings to align thing
nicely. You can do that by making enough spaces, or looking at the
things you can do with a format string and field alignment.

Write some code and come back with further questions.

Nobody here will be providing you directly with solutions (learning from
homework is done by solving the problem yourself) but we are happy to
help when you have made an attempt and are having problems, or to
suggest approaches if you can’t see how to start.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

do you mean something like this,

([(s[0:i], s[((x := len(s)) - i):x]) for i in range(1, 6)])

one variation could have been,

([(s[0:i], s[(x - i):x]) for i in range(1, (x:=len(s))+1)])

but it would give the error,

SyntaxError: assignment expression cannot be used in a comprehension iterable expression

which probably will get fixed in some future version of python

I think slicing is well explained here:

hint
text = 'Happy'
print(text[:1], text[-1:])
print(text[:2], text[-2:])

You can then get the length of the string, and print the slices in a for loop.

What have you tried?

What does this do when you try it?

word = "Happy"
print(word[:1], word[-1:])
print(word[:2], word[-2:])

@Kaliswaran, you can ignore the following. It is just a reply to @vainaixr.

I think it is off-topic here because such complex expressions and using comprehensions can give probably more confusion than help to a beginner but: You do not need to call len() multiple times.

Cleaned up, as a bonus showing possibility of replacing range(1, len(...)) by enumerate():

[
    (text[:i], text[-i:])
    for i, _ in enumerate(text, start=1)]
1 Like

Hi Steven,
I tried your suggestion, I actually got it, but not fully, it throws error after certain stage, please kindly check with this screenshot I attached with this.

Hi Everyone,
I tried Steven’s suggestion,
I actually got it, but not fully, it throws error after certain stage, please kindly check with this screenshot I attached with this. so any one can sort out this.

Please do not send text in images. It is difficult to work with images. Copy the text and paste it between triple backticks. In your message editor it will look like this:

My code:
```
# paste your Python code here
```

My error message:
```
# paste your error message here
```

Anyway, focus on the error message. It complains about unmatched ')'.

In your program (as in mathematic formulas) all the brackets must be matched (left one with the right one). Check that.

Also notice that the code is not exactly the same as I and Steven posted. It will give different results.

Thanks for your guidance.
Actually I done a mistake on brackets that as you told earlier. So I make that correct on that and now code works fine with proper output. Thanks.
My code:

word = "Happy"
print(word[0], word[-1])
print(word[0:2], word[-2:])
print(word[0:3], word[-3:])
print(word[0:4], word[-4:])
print(word[0:5], word[-5:])
2 Likes

That is great! Congratulations!

Notice that when you slice the beginning of a string (or other sequence like list) you can omit the first 0 and you can make all the slices look the same except the changing index:

print(word[:1], word[-1:])
print(word[:2], word[-2:])
...

If you learned for loops (or when you learn them) you can improve the program to use just a single print inside a loop…

2 Likes