String is a sequence of characters which is enclosed within quotes.
in python we use strings in 3 ways :
1. single quoted : a = 'name'
2. double quoted : a = "name"
3. triple quoted : a = ''' name '''
String slicing : A string can be liced in python to get a part of the string.
name = "N A M E" : Length is 4
The index in a string starts from 0 to range ( length-1).
In order to slice a string, follow syntax:
sl = name [ind_start : ind_end]
ind_start : first index included
ind_end : last index is not included.
sl[0:3] returns "name" : characters from 0 to 3
sl[1:3] returns "ame" : characters from 1 to 3
Negetive Indices : These can also be used as , for above example : -1 corresponds to range (length-1) index, -2 corresponds to (length-2) index, so on..
Slicing with a skip value : we can provides a skip value as a part of our slice like this:
word = "amazing"
word [1:6:2] is 'mzn'
other advanced slicing techniques
wrod ="amazing"
word[:7] : word [0:7] is 'amazing'
word[0:] : word[0:7] is 'amazing'
string functions : some of the mostly used functions to perform operations on or manipulate strings are :
1. len( ) :it returns length of the string. len("God") : returns 3.
2.stringendswith( ) this function tells wether variable string ends with the given string or not.
stringendswith("od") : returns true for "od" since god ends with "od"
3. string count ( ) : its counts the total number if occurance of any character.
stringcount("g") : returns 1
4. stringcapitalize( ) : this function capitalizes the first character of a given string.
5. stringfind(word) : this function finds a word and returns the index of first occurance of that word in the string.
6. stringreplace(oldword, newword) : this function replaces the oldword with newword in the entire string.
Escape Sequence Character:
Sequence of character after backslash '\' comprises of more than one characters but represents one character when used within the strings.
\n for new line
\t for tab
etc.
Programs
1. #Strings
# b = "Praveen's" # --> Use this if you have single quotes in your strings
# b = 'Praveen's
b = '''Praveen"s and
Praveen's'''
print(b)
# print(type(b))
2. #string slicing
# greeting = "Good Morning, "
# name = "Harry"
# print(type(name))
# Concatenating two strings
# c = greeting + name
# print(c)
name = "Praveen"
# print(name[4])
# name[3] = "d" --> Does not work
# print(name[1:4])
# print(name[:4]) # is same as name[0:4]
# print(name[1:]) # is same as name[1:5]
# c = name[-4:-1] # is same is name[1:4]
# print(c)
name = "PraveenIsGood"
# d = name[0::3]
d = name[:0:-1]
print(d)
3. #String functions
story = "once upon a time there was a youtuber named Harry who uploaded python course with notes Praveen"
# String Functions
# print(len(story))
# print(story.endswith("notes"))
# print(story.count("c"))
# print(story.capitalize())
# print(story.find("upon"))
print(story.replace("Praveen", "cstechiie"))
4. #Escape Sequences
story = "Harry is good.\nHe\tis ve\\ry good"
print(story)