Inputs and Outputs Basics

Take Input From User

input()
allows flexibility to take the input from the user. Reads a line of input as a string.

Code

username = input()
print(username)
PYTHON

Input

Ajay

Output

Ajay

Working with Strings

String Concatenation

Joining strings together is called string concatenation.

Code

a = "Hello" + " " + "World"
print(a)
PYTHON

Output

Hello World

Concatenation Errors

String Concatenation is possible only with strings.

Code

a = "*" + 10
print(a)
PYTHON

Output

File "main.py", line 1
a = "*" + 10
^
TypeError:
can only concatenate str (not "int") to str

String Repetition

*
operator is used for repeating strings any number of times as required.

Code

a = "*" * 10
print(a)
PYTHON

Output

**********

Code

s = "Python"
s = ("* " * 3) + s + (" *" * 3)
print(s)
PYTHON

Output

* * * Python * * *

Length of String

len()
returns the number of characters in a given string.

Code

username = input()
length = len(username)
print(length)
PYTHON

Input

Ravi

Output

4

String Indexing

We can access an individual character in a string using their positions (which start from 0) . These positions are also called as index.

Code

username = "Ravi"
first_letter = username[0]
print(first_letter)
PYTHON

Output

R

IndexError

Attempting to use an index that is too large will result in an error:

Code

username = "Ravi"
print(username[4])
PYTHON

Output

IndexError: string index out of range

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form