String is a collection of characters. It is stored in sequence as an array. Normally a string in python is assigned a value by the following syntax.
Syntax:
String_Variable= " String value "
Eg:
a= " Best wishes"
where, a is a variable that represents string. "Best wishes" is the value assigned to string.
Next, a simple python program to display this string is given below.
a="Best wishes"
print(a)
The Program and its output are like this.
- Extracting a character or set of characters.
- Finding the total number of characters (Length) in a string
- Converting upper case to Lowercase and vice versa.
- Adding two strings
- Replacing characters
- Splitting the string into sub string
- White space removing
The sample code is given as below.
- Extracting a character or set of characters.
a="Best Wishes"
print (a[5:11])
It extracts "Wishes" from String a and displays it on the screen.
- Finding the total number of characters (Length) in a string
a="Best Wishes"
print(Len(a))
This code gives the output as 11.
- Converting upper case to Lowercase and vice versa.
a="best wishes"
print (a.upper())
This gives the uppercase of the string a. That will be "BEST WISHES".
b="WELCOME"
print (b.lower())
output is "welcome".
- Adding two strings
a="Hi"
b="Hello"
print(a+b)
It gives you "HiHello" as output.
- Replacing characters
a="Good"
print(a.replace("G","F"))
This code replaces the "G" to "F". Hence the output is "FOOD"
- Splitting the string into sub string
a="Best wishes"
b=a.split(" ")
print (b)
split function splits the string based on the white space in the string here.
The space is between Best and wishes. So, the output is [ 'Best' 'wishes']
- White space removing
a=" Welcome "
print(a.strip())
This code removes the white space in the beginning and the end. Here, the output is " Welcome".
These are the basic string operations in python.
No comments:
Post a Comment