Strings are sequences of characters, and in Python, they are written between single quotes (‘) or double quotes (“”). We can perform specific tasks on a string. Let’s perform some operations.
Length of a String: We can find the length of a string using len() function.
code = "python"
len1 = len(code)
print("Python is a", len1, "letter word.")
The Output Of This Code Will Be:
Python is a 6 letter word.
Why string is an array?
Treating strings as arrays means that you can access each character in the string through a specific index. We can manipulate the individual characters in the string. Like in arrays, every character in strings also has a position, which we call an index, and this index starts from 0. For example:
var = "Python"
print(word[0]) # Output: P
print(word[1]) # Output: y
Here, var is a string and we wrote the word[0], which means we accessed the first character of the string, which is ‘p’. But there is an important difference, strings in Python are immutable. It means after creating a string we can’t change it. In this, we cannot make direct changes at the character level, unlike in some other programming languages.
Now let’s perform a slicing operation on a string
programming = "javascript"
print(programming[:5]) #Slicing from Start
print(programming[5:]) #Slicing till End
print(programming[2:6]) #Slicing in between
print(programming[-8:]) #Slicing using negative index
- [:5] extracts characters from the beginning up to index 5 (exclusive). Output: javas
[5:]
extracts characters starting from index 5 till the end of the string. Output:cript
- [2:6] extracts characters from index 2 to index 5 (6 is exclusive). Output: vasc
- [-8:] extracts characters from 8 positions from the end to the end. Output: ascript
The Output Of This Code Will Be:
javas
cript
vasc
vascript
Loop through a String:
programming = "python"
for i in programming:
print(i)
programming
is a variable assigned the value"python"
.- This is a
for
loop that iterates over each character (i
) in the stringprogramming
. - In each iteration, the loop prints the current character.
The Output Of This Code Will Be:
p
y
t
h
o
n
If you don’t know the best feature of Python, that is “How to take input from users” just click on read more.
I hope you understand how to take Input From users in Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.