-1

While learning variables in Python I came across this - if I define a variable name = "Youtube"

What will be the code if I want to print t and b?

I know name[3:6] = "tub"? But I need to know what do I need to do in order to get t and b as output.

destructioneer
  • 150
  • 1
  • 10
  • 2
    To do this, you need to understand how to cut and slice [string](https://www.pythoncentral.io/cutting-and-slicing-strings-in-python/). You can access those letters by index or by matching them in a for loop. – Jose M. González Jul 07 '23 at 07:26
  • Thanks a lot for the answer. Will learn slicing now – Vasudev Sinha Jul 10 '23 at 16:11

4 Answers4

1

Strings work the same way as lists in Python.

s = "Youtube"
print(s[0])

Will show the first thing contained in your string: Y

print((s[0:2])

Will show from first to n-1 (so from 0 to 1) : Yo

If you want to print the 'b' and the 't', you need to call :

print(s[5]+s[3])
m4lou
  • 47
  • 1
  • 10
1

Many ways to skin this cat. Understanding slice notation is definitely a starting point.

name = "Youtube"
sub = name[3:6]  # "tub"

Even more basic is accessing individual elements by index:

x = name[3]  # "t"
y = name[5]  # "b"

Also helpful, particular to get edge elements, is unpacking:

x, _*, y = sub  # will get t and b respectively

This does: of the iterable sub, assign the first element to x, the last one to y, and what ever is in between to an anonymous list _. No need to know the length of sub in advance and works with iterators where you wont be able to use slices or negative indexing.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Use print(name[3] + name[5]). That prints the 4th and 6th letter in the string.

destructioneer
  • 150
  • 1
  • 10
0

First of all, consider not naming a variable name (it may confuse you later on).

Two choices for this specific case:

x = "Youtube"
>>> print(x[3]+x[5])
tb

or

>>> print(x[3::2])
tb

"Youtube"[3::2] means start at index 3 (first index is 0, so position 3 is 't' and from then on every second index until there is nothing left.)

"Youtuber"[3::2] would result in 'tbr' instead.

srn
  • 614
  • 3
  • 15