Necessity of input function comes when you want to get some text from user. So it will wait for the user to enter some text. Have a look at below program.
In line 2 we are prompting user to enter a name, here we are using input() function. In line 3 we are printing the name to console again. Even input() function without prompt message also serves purpose, Checkout below problem:
print(“welcome to learn mode on, “,name)
welcome to learn mode on, shifu
len() function is used to find the length of the string value passed to it. Input must be of string type. Otherwise compiler will scold you with type error. Output will be the integer i.e., length of string.
Try below possibilities as well:
print(“length is ” ,len(“shifu”)) #5
print(“length is ” ,len(“”)) #0
print(“length is ” ,len(” “)) #1
print(“length is ” ,len(9)) #error
Now next move to know about slice operator. I need first four letters of the input string. How do we achieve that? Here we go: stringname[startingindex:EndingIndex+1]. Lets discuss few check points before going ahead:
- Indexing always starts with 0 (When we are moving from left to right)
- Indexing will start from -1 (When we are moving from right to left)
- If the range is [1:5] , output will include string from index 1 to 4. Character in position 5 will be excluded always.
- If we did not mention ending index slice will return till the ending of the string. If both starting and ending indexes are missing then it will return entire string.
- Space will also take position of index. Below is the indexing structure of string “Master Shifu”. Lets extract sub strings in various ways.
Code is pretty much self explanatory. Do try some more examples. Comment us if you are having any queries on this post.