- What is a string?
String:- Collection of character or any sequence of character.
- String data type in python: String is the most commonly used object in any programming language.
- In any type of application, it may be small or large the string is most commonly used.
- Python string: Any sequence of characters specified within single or double quotes.
- String example:-
- Default convention is a single quote.
Using single or double quote we can write only a single line string.
Note: – Even you write single character within quoted it is also considered as the string in python.
In the above example, it may be a character type in other languages, but in python, it is a string type.
- There is no character type in python.
- Multi-line string literal also we can write in python, using triple quotes (single or double)
- String in python example: –
seek’ => invalid
seek’’’ => valid
seek””” => Valid
- Writing String literals using triple quotes will be helpful if you want to print double or single quotes in the string.
- You can print quotes within a string literal.
- You can use triple single or double quotes.
“welcome to “ Technicalseek” site”
“”“welcome to “ Technicalseek” site”””
- Or You can use mismatch quotes
“Welcome to ‘Technical seek’ sire”
- Or you can use \ (Escape character) to print quotes
‘This is \’ quote’
- Python String program
Program to accept some string from keyboard and print all characters in a string with its positive and negative index.
string in pythonPython12345S=input("Enter some string = ")I=0for x in S:print("The character at index ",I ," is " ,x)I= I+1
How to access characters from string
- Using index
- Using slice operator
- You can access character by index.
- Index in python: positive index or negative index
- Positive index: – forward direction (left to right)
- Negative index: – backward direction (right to left)
- In case you access the invalid index, you will get an error.
- Slice operator is used to accessing string.
- Syntax: –
S[begin: end: step]
- From the beginning index to end-1 index and every time increment by 1
S[0: 7: 1]
Read also slice operator in python
Mathematical operator, we can apply for the string
- + operator and * operator we can apply for the string.
- + operator (concatenation)
Two strings are concatenated.
S=”technical “+” Seek” => technical Seek
I’d you want to apply+operator for the str type then both arguments should be the strong type if anyone argument is of other types, then you will get an error.
S=”technical ” + 2 => Error
String repetition operator
If you want to apply * operator for str type, then the compulsory one argument must be of type integer.
You can write in any form
String functions in python
1. Length function in python
- python string length
string length in python: The python contains the inbuilt function to know the length of a string.
- String length syntax
- String length example
find a length of string
l=len(S) => 6
2. Python string comparison
- Comparison operators for the string are used to compare two strings
- Comparison operator in python are >, >=, <, <= we can use.
==, ! = equality operator also we can use.
- These operators are always gone check alphabetic or Unicode order.
A-> 65 a->97
- Program to compare two strings
python stringPython12345678S1=input ("Enter first string = ")S2=input("Enter second string = ")if S1==S2:print ("Both string are equal")elif S1<S2:print("First string smaller than second")else:print("First string greater than second")
- == operator meant for content comparison.
3. Strip function in python
- Strip removes the unnecessary spaces from the string.
- Python strip function : In python there are 3 method available for this lstrip(), rstrip() and strip()
- Lstrip function
To remove the spaces present at the beginning (at left)
- Rstrip function
To remove spaces at the end
- Strip function
To remove spaces at the beginning and end.
- Strip function example
strip in pythonPython1234567city=input ("Enter city = ")list=['PUNE','HYD','MUM']if city.strip() in list:print("City available in list")else:print("City not available in list")
4. Python string find or Find()
- To find the substring in a string.
Find(substring, startindex, endindex)
- Python string find example
Find index at which substring presentpython find functionPython12345678910111213S=input("Enter string = ")subs=input("Enter substring = ")flag=FalsePos=-1N=len(S)while True:Pos=S.find(subs, Pos+1, N)if Pos==-1:breakprint("Substring = ", subs," found at index = ", Pos)flag=Trueif flag==False:print("Substring not found ")
5. Python string count
- To count a number of times the substring present in the string.
- Counting substring in string
- To find the substring in range
count(substring, begin, end) from begin index to end index how many times substring is present.
S. Count(‘seek”, 8,15)
6. Replace function in python
- Python string replace : Replace the string with another string.
String. Replace (old string, new string)
- Python string replace example
S=”Learning python is difficult”
S=S.replace(“difficult “, ” Easy”)
Purpose of replace function in python
String object are immutable in python, we can not modify the existing object. Whenever we perform modifications new object is created with changes.
print(“String= ” , S, ” Address is = “, id(S))
print(“String= ” , S1, ” Address is = “, id(S1))
Even using replace () function, existing object is not changed instead it creates new.
We can write it as
print(“String= ” , S, ” Address is = “, id(S))
print(“String= ” , S, ” Address is = “, id(S))
In this case, whenever we perform replace new object got created with modification and as we assigning some reference var to object, then the existing reference will point to new object.
7. Split function python
- To split the string according to the given separator.
String. Split (separator)
- But default Separator is space.
- split function example
split pythonPython12345S='02-03-2019'L= S.split('-')print(L)for x in L:print(x)
8. Reverse split
- To reverse split.
- Syntax:- Rsplit ()
L. S. Split(”, 3)
L. Rsplit(”, 2)
9. Join function in python
- Python join: Join strings into a single string with respect to the separator.
- You can join list or tuple.
- Python join two strings
- Python join example
join function in pythonPython12345print(" ---- join function in python ")L=['technical', 'seek']print("Before Join = ",L)S='-'.join(L)print("After Join = ",S)
10. Changing case of string
- Following are functions for changing case in python
- Upper(): to convert to uppercase
The string upper() method converts all lowercase characters in a string into uppercase characters and returns it.
The syntax of upper() method is:
where String is converted into upper case.
The upper() method returns the upper cased string from the given string
Python String Upper() Example
Convert a string to uppercaseConvert a string to uppercasePython123string = "technical seek"print("String = ",string)print("Upper case string = " ,string.upper())
- Lower(): to convert to lowercase
The string lower() method converts all uppercase characters in a string into lowercase characters and returns it.
The syntax of lower() method is:
where String is converted into lower case.
The lower() method returns the lower cased string from the given string
Python String lower() Example
Convert a string to lower case
Python String lower()Python123string = "TECHNICAL SEEK"print("String = ",string)print("Upper case string = " ,string.lower())
- Swapcase(): to convert to opposite case.
The string Swapcase() method converts all lowercase characters in a string into uppercase characters and uppercase characters in a string into lowercase characters and returns it.
The syntax of Swapcase() method is:
where String is converted into opposite case.
The swapcase() method returns the string after changing case.
Python String swapcase() Example
Convert a string to opposite caseSwapcase case stringPython123string = "TECHNICAL seek"print("String = ",string)print("Swapcase case string = " ,string.swapcase())
- Title() every word start with uppercase.
The string Title() method converts all first character in word into uppercase characters and returns it.
The syntax of Title() method is:
Python String Title() Exampletitle() in pythonPython123string = "technical seek site "print("String = ",string)print("Swapcase case string = " ,string.title())
- Capitalize(): only first letter in capital case.
The string Capitalize() method converts first character in String into uppercase characters and returns it.
The syntax of Capitalize() method is:
Python String Capitalize() Examplecapitalize() in pythonPython123string = "technical seek site "print("String = ",string)print("Swapcase case string = " ,string.capitalize())
- To know object available in use.
In Operator in pythonPython123456City= input("Enter your city name = ")Li=['HYD', 'PUNE', 'MUM']if City in Li:print("City available in List")else:print("City not available in List")
- In above example, whenever we enter input from keyboard we enter city name direct.
But in some country or some people (philand) they enter space before entering city name.
- In this case, user entered valid city name (with her space) , it shows error as we only compares character not space. see in below output image
- But this is wrong as city is valid, so in this case developer need to check for this scenario.
- To remove this you need to use strip method in python.
Difference between sep and split
- Split is applicable related to strong object.
- And separate is applicable to print function.
- Therefore while printing space is separator but if you don’t want space as separator then use sep operator.