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.
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.
 
    
     
    
    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])
 
    
    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.
 
    
    Use print(name[3] + name[5]). That prints the 4th and 6th letter in the string.
 
    
    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.
