Python Strings & Operations
Python Strings & Operations
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though
you may see characters on your screen, internally it is stored and manipulated as a
combination of 0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is
decoding. ASCII and Unicode are some of the popular encodings used.
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
str = 'computer'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
output:
str = computer
str[0] = c
str[-1] = r
str[1:5] = ompu
str[5:-2] = te
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.
# Python String Operations
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
output:
We can iterate through a string using a for loop. Here is an example to count the number of 'l's
in a string.
output:
3 letters found
We can test if a substring exists within a string or not, using the keyword in.
Various built-in functions that work with sequence work with strings as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function
returns an enumerate object. It contains the index and value of all the items in the string as
pairs. This can be useful for iteration.
Similarly, len() returns the length (number of characters) of the string.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
output: