A String can be defines as a sequence of characters.
For accessing the characters of a string square brackets[ ] are used.
event='wedding'
letter=event[4]
print(letter)
The above code will give you the charachter at position 4.
The square bracket consist an expression known as index.
i
Now you might be confused, as we count i is at position 5 so why the output at position 4 is equal to i?
This is because the index is an offset from the beginning of the string, and the offset of the first letter is 0.
That's why it is printing i as output.
So w is the 0th word,e is the 1st word,d is the 2nd word and so on.
String literals can be sorrounded by single quotation marks or double quotation marks.
As "wedding" is same as 'wedding'
Important points about strings:
s='str'
k='ing'
m=s+k
print(m)
Output:
string
m='12345'
k=int(m)
print(k)
Output:
12345
A segment of a string is called a slice. Selecting a slice is similar to selecting a character.
s='Deep Learning'
print(s[0:7])
Output:
Deep Le
There is also an term Negative indexing.
In negative indexing,the indexes taken are negative and in output ,counting starts from ending.Let's take an example.
m='Machine'
print(m[-5:-2])
The above code says that Get the characters from position 5 to position 1 (not included), starting the count from the end of the string.
chi
To measure the length of the string we will use the len() function.
Example:a="artificial"
print(len(a))
Output:10
Python has a set of various built-in methods that can be used on strings.Some of them are following:
The method lower() is used to convert the string in lowercase.
Example:m='MACHine'
print(m.lower())
Output:
machine
The method lower() is used to convert the string in uppercase.
Example:m='MACHine'
print(m.upper())
Output:
MACHINE
The method strip() is used to remove any whitespace from beginning or last.
Example:m=' MACHine '
print(m.strip())
Output:
MACHine
The method split() is used to split out the string into substrings with the help of instances of the seperator.
Example:m='artificial,intelligence'
print(m.split(','))
Output:
['artificial','intelligence']
Note: If any seperable is not provided in the split() function then it uses whitespace as an default seperable.
The method startswith() is used to give the output in True or False.This function will check the given string is starts with the given input or not.
Example:m='Hello, welcome to my website'
print(m.startswith("Hello"))
Output:
True
There are lots of these type of functions available in python which are very useful.