Write about strings and input in python. Explain with 2 examples.
String in Python:
A string is a sequence of characters.In Python, a string is a sequence of Unicode characters.
creating a string in
Python:
Strings can be created by enclosing characters inside a single
quote or double-quotes.
Example:
# defining strings in Python
my_string = 'Hello'
print(my_string)
>> Hello
my_string = "Hello"
print(my_string)
>> Hello
Access characters in a
string:
We can access individual characters using indexing and a range of
characters using slicing.
The index of -1 refers to the last item, -2 to the second last item
and so on. We can access a range of items in a string by using the
slicing operator (:).
Example:
#Accessing string characters in
Python
str = 'AGGREGATE ' ''
print('str = ', str)
#first character
print('str[0] = ', str[0])
>> A
#last character
print('str[-1] = ', str[-1])
>> E
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
>> GGRE
#slicing 6th to 2nd last
character
print('str[5:-2] = ', str[5:-2])
>> GA
String
Operations:
Concatenation of Two or More Strings
:
Joining of two or more strings into a single one is called
Concatenation.
The + operator does this in Python.
Simply writing two string literals together also concatenates
them.
The * operator can be used to repeat the string for a given number
of times.
Example:
# Python String Operations
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
>> HelloWorld!
# using *
print('str1 * 3 =', str1 * 3)
>> HelloHelloHello
Iterating Through a
string:
Iterate through a string using a for loop:
Example:
# Iterating through a string
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
>> 3 Letters found
Python Input:
In Python, we have the input() function to allow this. The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is
optional.
Example:
name = input('What is your name?
')
What is your name? chandu
>>> name
'chandu'
>>> num = input('Enter a
number: ')
Enter a number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a
number. To convert this into a number we can use int() or float()
functions.
>>> int('10')
10
>>> float('10')
10.0
Get Answers For Free
Most questions answered within 1 hours.