0% found this document useful (0 votes)
25 views5 pages

Python String - UNIT 3

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

Python String [] Slice - Gives the character from a[1] will give

the given index e

[:] Range Slice - Gives the a[1:4] will


characters from the given range give ell
String is a group of characters (May be digit, special
character, alphabets or any other character) in Membership - Returns true if a H in a will
character exists in the given give 1
We can create string by enclosing characters in single quotes string
the same as double quotes.
not in Membership - Returns true if a M not in a
var1 = 'Hello World!' character does not exist in the will give 1
var2 = "Python Programming" given string

String are stored in continuous memory location % Format - Performs String See at next
formatting section

String Formatting Operator

One of Python's coolest features is the string format operator


%.
This operator is unique to strings and makes up for the pack
of having functions from C's printf() family.

Following is a simple example −


Accessing Values in Strings
print "My name is %s and weight is %d kg!" % ('Zara', 21)
var1 = 'Hello World!'
var2 = "Python Programming" When the above code is executed, it produces the
following result −
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5] My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used


along with % −

Format Conversion
Symbol

%c character
String Special Operators

Assume string variable a holds 'Hello' and variable b holds


'Python', then − %s string conversion via str() prior to
formatting
Operator Description Example

+ Concatenation - Adds values on a + b will


%i signed decimal integer
* Repetition - Creates new a*2 will give
strings, concatenating multiple -HelloHello
copies of the same string %d signed decimal integer
%u unsigned decimal integer
output
15
15
%o octal integer
-1
3. lower() The method lower() returns a copy of the string in
which all case-based characters have been lowercased.
%x hexadecimal integer (lowercase letters)
4. upper() returns a copy of the string in which all case-based
characters have been uppercased.
%X hexadecimal integer (UPPERcase letters) Syntax: str.lower()
Return value : String
Argument type :NA
%e exponential notation (with lowercase 'e')
str = "THIS IS STRING EXAMPLE ... WOW!!!";
print str.lower()
%E exponential notation (with UPPERcase
'E') output : this is string example. .. wow!!!

str = "this is string example. .. wow!!!";


%f floating point real number print "str.upper() : ", str.upper()

output :THIS IS STRING EXAMPLE ... WOW!!!

comparison operator
All Relational operator (< <= > >= == != )apply on string 5.isalnum() :The method isalnum() checks whether the string
also consists of alphanumeric characters.

String Handling Function in Python Syntax: str.isalnum()

1. capitalize() It returns a copy of the string with only its first Return Value
character capitalized. This method returns true if all characters in the string are
Return value : String alphanumeric and there is at least one character, false
Argument type :NA otherwise.

str = "this is string example. ..wow!!!"; str = "this2009"; # No space in this string
print "str.capitalize() : str = "this is string example. .. wow!!!"; print str.isalnum()
output
str = "this is string example. .. wow!!!";
str.capitalize() : This is string example. .. wow!!! print str.isalnum()

2. find()It determines if string str occurs in string, or in a output


substring of string if starting index beg and ending True
index end are given. False

Syntax : str.find(str, beg=0, end=len(string)) isalpha() The method checks whether the string consists of
str − This specifies the string to be searched. alphabetic characters only.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the Syntax: str.isalpha()
length of the string.

Return Value str = "this"; # No space & digit in this string


Index if found and -1 otherwise. print str.isalpha()

str1 = "this is string example....wow!!!"; str = "this is string example. .. wow!!!";


str2 = "exam"; print str.isalpha()
print str1.find(str2)
output:
print str1.find(str2, 10)
print str1.find(str2, 40) true
false str.isspace()
isdigit() The method isdigit() checks whether the string return true/false
consists of digits only.
str = " ";
str.isdigit() print str.isspace()

str = "123456"; # not work with space str = "This is string example. .. wow!!!";
print str.isdigit() print str.isspace()

str = "this is string example. .. wow!!!"; output


print str.isdigit() true
false
output
True len() The method len() returns the length of the string.
False
str = "this is string example. .. wow!!!";
print "Length of the string: ", len(str)
islower() The method islower() checks whether all the case- output
based characters (letters) of the string are lowercase. Length of the string: 32
str.islower()
return true /false
isupper() The method isupper() checks whether all the case-
str = "THIS is string example.... wow!!!"; based characters (letters) of the string are uppercase.
print str.islower()
str.isupper()
str = "this is string example. .. wow!!!";
print str.islower()
str = "THIS IS STRING EXAMPLE ...WOW!!!";
output print str.isupper()
false
true str = "THIS is string example. .. wow!!!";
print str.isupper()
isnumeric() The method isnumeric() checks whether the
string consists of only numeric characters. This method is True
present only on unicode objects. False
Note − To define a string as Unicode, one simply prefixes a
'u' to the opening quotation mark of the assignment. Below is
the example. lstrip() The method lstrip() returns a copy of the string in
which all chars have been stripped from the beginning of the
string (default whitespace characters).
str.isnumeric()
str.lstrip([chars])
return true /false

str = u"this2009"; str = " this is string example....wow!!! ";


print str.isnumeric() print str.lstrip()
str = "88888888this is string example. .. wow!!!8888888";
str = u"23443434"; print str.lstrip('8')
print str.isnumeric()
output
output this is string example. .. wow!!!
False this is string example. .. wow!!!8888888
True

isspace() The method isspace() checks whether the string


consists of only and only space,then return true otherwise rstrip() The method rstrip() returns a copy of the string in
which all chars have been stripped from the end of the string
false.
(default whitespace characters).
str.rstrip([chars])
txt = "hello, my name is Peter, I am 26 years old"
str = " this is string example....wow!!! "; >>> x = txt.split(", ")
print str.rstrip() >>> x
str = "88888888this is string example. .. wow!!!8888888"; ['hello', 'my name is Peter', 'I am 26 years old']
print str.rstrip('8')

this is string example. .. wow!!! The following diagram depicts how the string modulo
88888888this is string example... wow!!! operator works:

strip() The method strip() returns a copy of the string in


which all chars have been stripped from the beginning and the
end of the string (default whitespace characters).

str.strip([chars]);

On the left side of the "string modulo operator" is the so-


called format string and on the right side is a tuple with the
str = "0000000this is string example. .. wow!!!0000000"; content
print str.strip( '0' )

this is string example. .. wow!!!

split() The split() method splits a string into a list. The format string contains placeholders. There are two of
those in our example: "%5d" and "%8.2f".
You can specify the separator, default separator is any
whitespace. The general syntax for a format placeholder is

Note: When max is specified, the list will contain the


specified number of elements plus one %[flags][width][.precision]type

string.split(separator, max)
Let's have a look at the placeholders in our example
str.split(str="", num=string.count(str)). This is followed by the total number of digits the string
should contain. This number includes the decimal point and
all the digits. i.e. before and after the decimal point.
Parameter Description

separator Optional. Specifies the separator to use when


splitting the string. Default value is a
whitespace

max Optional. Specifies how many splits to do.


Default value is -1, which is "all
occurrences"

Python Program - Count Character in String

print("Enter 'x' for exit.");


>>> txt = "apple#banana#cherry#orange" string = input("Enter any string to count character: ");
>>> x = txt.split("#", 1) if string == 'x':
>>> x exit();
['apple', 'banana#cherry#orange'] else:
>>> x = txt.split("#", 2) char = input("Enter a character to count to count from above
>>> x string: ");
['apple', 'banana', 'cherry#orange'] val = string.count(char);
print("Total = ",val); else:
newstr = string;
# Python Program - Find Length of String print("\nRemoving vowels from the given string...");
vowels = ('a', 'e', 'i', 'o', 'u');
for x in string.lower():
print("Enter 'x' for exit.") if x in vowels:
string = input("Enter a string to find its length: ") newstr = newstr.replace(x,"");
if string == 'x': print("New string after successfully removed all the vowels:");
exit(); print(newstr);
else:
print("\nLength of the string =", len(string))
# Python Program - Remove Punctuations from String

# Python Program - Compare Two Strings print("Enter 'x' for exit.");


string = input("Enter any string to remove all punctuations: ")
if string == 'x':
print("Enter 'x' for exit.") exit();
string1 = input("Enter first string: ") else:
if string1 == 'x': newstr = string;
print("\nRemoving punctuations from the given string...");
exit(); punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''';
else: for x in string.lower():
string2 = input("Enter second string: ") if x in punctuations:
if string1 == string2: newstr = newstr.replace(x,"");
print("New string after successfully removing all punctuations\n");
print("\nBoth strings are equal to each other.") print(newstr);
print(string1,"==",string2);
else:
print("\nStrings are not equal.")
print(string1,"!=",string2);
# Python Program - Remove Word from Sentence
# Python Program - Copy String print("Enter 'x' for exit.");
string = input("Enter any string to remove particular word: ");
print("Enter 'x' for exit."); if string == 'x':
string = input("Enter any string to copy: "); exit();
if string == 'x': else:
exit(); word = input("Enter word to be delete/remove: ");
else: print("\nDeleting given word from the given string...");
print("Copying string 1 (string) into string 2 (cstring)..."); print("New String after successfully deleting",word);
cstring = string; word_list = string.split();
print("\nString 2 after successfully copied =",cstring); print(' '.join([i for i in word_list if i not in word]));
print("\nString 1 =",string,"\nString 2 =",cstring);

# Python Program - Count Character in String

print("Enter 'x' for exit.");


string = input("Enter any string to count character: ");
# Python Program - Reverse String if string == 'x':
exit();
print("Enter 'x' for exit."); else:
string = input("Enter any string to reverse it: ") char = input("Enter a character to count to count from
if string == 'x': above string: ");
exit(); val = string.count(char);
else: print("Total = ",val);
revstring = string[::-1];
print("\nOriginal String =",string);
print("Reversed String =",revstring);

# Python Program - Remove Vowels from String

print("Enter 'x' for exit.")


string = input("Enter any string to remove all vowels from it: ")
if string == 'x':
exit();

You might also like