Strings in Python

A variable can be assigned a string or a character.

str1="This is a string"
str2=' key'
str3=""" this is a string"""

Multiple strings can be printed in a single line by,

str1="This is a string"
str2=' key'
str3=""" this is a string"""
print(str1+str2+str3)

**Escape sequence characters -**Are specified characters that are used to sequence the string within quotes.Next line- \n tab- \t

Default string functions in python is-Here are some of the default string functions in Python:

len(): - Returns the length of a string. print(len(str1))

str(): - Converts an object to a string.

lower(): - Converts a string to lowercase. upper(): - Converts a string to uppercase. str1.upper().

strip(): - Removes whitespace from the beginning and end of a string. str1.strip().

split(): - Splits a string into a list of words. str1.split()

join(): - Joins a list of strings into a single string. "#".join(str1).

find(): - Finds the first occurrence of a substring in a string. str1.find("hi").

replace(): - Replaces all occurrences of a substring in a string with another substring. str1.replace("a", "b").

format(): - Formats a string according to a specified format.

Indexing-When a string is assigned in python each letter is given a number value it is called indexing.

ch=str1[2]

print(ch) #prints i from str1 you cannot replace the character using indexing.

Slicing-Accessing parts of a string

str="dayday"

str[0:2] is "mon"

Slicing can also be done by using negetive numbers which will return the last characters from the string.

Other String Functions str.endsWith(“er.“) #returns true if string ends with substr str = “I am a coder.”

str.count(“am“) #counts the occurrence of substr in string str.capitalize( ) #capitalizes 1st char

str.find( word ) #returns 1st index of 1st occurrence str.replace( old, new ) #replaces all occurrences of old with new.

Q1 Write a program to play around with strings.

a=input("Enter your name:")
print(len(a))
print(a.capitalize())
b=("!@##$%%$%^^&**()$^^%&$%^&%$")
print(b.count("$"))
print(a[0:2])
c=a.endswith("Em")
print(c)
d=a.count("Em")
print(d)
e=a.find('e')
print(e)
print(a.replace("a","b"))