String Manipulation in Python
Topics:
- Strings – introduction,
- Indexing
- String operations – concatenation, repetition, membership & slicing,
- Traversing a string using loops,
- Built-in functions: len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition(), split()
Strings in Python – Introduction
Python strings are characters enclosed in quotes of any type – single quotation marks, double quotation marks, triple quotation marks.
S = ‘Anjeev Singh Academy’ ,
T = “Singh@123”
Mline = ‘‘‘Anjeev Singh Academy
is the best free online academy on YouTube ’’’
Python strings is an immutable data type, i.e. not allowed to change in place. S[0] =‘R’ not allowed
String Indexing – Forward and Backward Indexing in Python
Strings are sequence of characters, where each character has a unique index number.
string = “mycstutorial.in”
>>> string[0]
‘m’
>>> string[-1]
‘n’
Two types of Indexing is supported in python.
(A) Forward Indexing and (B) Backward Indexing
The indexes of strings begin from 0 to length-1, in forward direction and -1, -2, -3, …. , -length in backward direction.
String operations – concatenation, repetition, membership & slicing,
Strings can be manipulated by using string operators. String operators are
Operator | Name | Description |
+ | Concatenation | Add two strings i.e. concatenate two strings. e.g. S = “Hello” + “Shyam” |
* | Replication / Repetition | Replicate the string upto n times. |
In / not in | Membership | To check given character exists in the string or not. |
[index] | Element Accessor | Extract the character from the given index position. |
[ : ] | Slicing [start:end:step] | Extracts the characters from the given range i.e start to stop |
==, !=, < , > , <=, >= | Relational / Comparison Operator | These relational operators can do comparison between strings, based on character by character comparison rules for Unicode or Ordinal Value |
Traversing a string using loops
Traversing a String or Text means accessing all characters of string, character by character, through its index position.
#Traversal of a string using loop name = "mycstutorial.in" for char in name: print (char, end=' ')
Output
m y c s t u t o r i a l . i n
Traversing a String using index position
#Traversal of a string using index - forward indexing name = "mycstutorial.in" for index in range(len(name)): print (name[index], end=' ')
Output
m y c s t u t o r i a l . i n
#Traversal of a string using index - backward indexing name = "mycstutorial.in" for index in range(-1, -len(name)-1, -1): print (name[index], end=' ')
Output
n i . l a i r o t u t s c y m
String Slicing
Slice means ‘a part of’. In Python, string slice refers to a part of string containing some contiguous characters from the string.
Syntax: string[start : end : step]
- where start and end are integers with legal indices.
- will return the characters falling between indices start and end. i.e. start, start+1, start+2,…, till end-1.
- By default value of step is 1. It is an optional argument.
Slice | Output, if str = “Hello Anjeev” |
str[ 2 : ] | ‘llo Anjeev” |
str[ : 5] | “Hello” |
str[4 : 8] | “o Anj” |
str[ : : 2] | “HloAje” |
str[ : : -1] | “veejnA olleH” |
str[-6 : -2 ] | “Anje” |
String Built-in functions
Python provides several built-in-methods to manipulate string.
Syntax : stringvariable.methodName( )
Example: isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), etc
Methods | Description | Example |
isalpha( ) | Returns True, if the string contains only letters, otherwise returns False. | >>>”abc”.isalpha() True >>>”1abc”.isalpha() False |
isalnum() | Returns True, if the string contains alphanumeric (i.e. alphabets or number or both), otherwise returns False | >>>”abc”.isalnum() True >>>”123″.isalnum() True >>>”a123″.isalnum() True >>>”@#2″.isalnum() False >>>”@#12ab”.isalnum() False |
isdigit( ) | Return True, if the string contains only digits, otherwise returns False. | >>>”123″.isdigit() True >>>”abc123″.isdigit() False |
isspace( ) | Returns True, if the string contains only spaces, otherwise returns False. | >>>” “.isspace() True >>>”a “.isspace() False >>>” a”.isspace() False |
islower( ) | Returns True if the string contains all lowercase characters, otherwise returns False. | >>>”mycstutorial.in”.islower() True >>>”MYCSTUTORIAL.IN”.islower() False |
isupper() | Returns True, if the string contains all uppercase characters, otherwise returns False | >>>”MYCSTUTORIAL.IN”.isupper() True >>>”mycstutorial.in”.isupper() False |
istitle( ) | Returns True, if string is properly “TitleCasedString”, otherwise returns False. | >>>”Anjeev Singh Academy”.istitle() True >>>”Anjeev singh academy”.istitle() False >>>”Anjeevsinghacademy”.istitle() True |
endswith() | Returns Ture, if string is ends with the given substring. | >>> name=”tanmay singh” >>> name.endswith(‘singh’) True >>> name.endswith(‘nh’) False |
startswith() | Returns True, if string is starts with the given substring. | >>> name=”tanmay singh” >>> name.startswith(‘tan’) True >>> name.startswith(‘tannu’) False |
len(string) | Returns the length of string, i.e. number of characters. | >>> name=”tanmay singh” >>> len(name) 12 |
capitalize() | Returns a copy of string with its first character capitalized. | >>> name=”tanmay singh” >>> name.capitalize() ‘Tanmay singh’ |
lower() | Returns a copy of string converted to lowercase. | >>> name=”TANMAY SINGH” >>> name.lower() ‘tanmay singh’ |
upper() | Returns a copy of string converted to uppercase. | >>> name=”tanmay singh” >>> name.upper() ‘TANMAY SINGH’ |
title() | Returns a copy of string converted to title case. | >>> name=”tanmay singh” >>> name.title() ‘Tanmay Singh’ |
swapcase() | Converts and returns all uppercase characters to lowercase and vice-versa. | >>> name=”Tanmay Singh” >>> name.swapcase() ‘tANMAY sINGH’ |
count() | Returns the number of times a specified value occurs in a string | >>> name=”tanmay singh” >>> name.count(‘a’) 2 |
find() | Returns the first occurrence of given string/character in the string. | >>> name=”tanmay singh” >>> name.find(‘y’) 5 |
index(char) | Search and returns the first occurrence of given character or substring. | >>> name=”tanmay singh” >>> name.index(‘y’) 5 |
lstrip() / lstrip(char) | Returns a copy of the string with leading characters removed. By default removed space. | >>> data = ‘ hello ‘ >>> data.lstrip() ‘hello ‘ >>> mesg = ‘aaaRAMaaa’ >>> mesg.lstrip(‘a’) ‘RAMaaa’ |
rstrip()/ rstrip(char) | Returns a copy of the string with trailing characters removed. By default removed space. | >>> data = ‘ hello ‘ >>> data.rstrip() ‘ hello’ >>> mesg = ‘aaaRAMaaa’ >>> mesg.rstrip(‘a’) ‘aaaRAM’ |
strip() | Returns a copy of the string with leading and trailing characters removed. | >>> data = ‘ hello ‘ >>> data.strip() ‘hello’ >>> mesg = ‘aaaRAMaaa’ >>> mesg.strip(‘a’) ‘RAM’ |
replace() | Returns a copy of the string with replaced old substring with new substring. | >>> name=”tanmay singh” >>> name.replace(‘singh’, ‘verma’) ‘tanmay verma’ |
split() | Splits the string at the specified separator, and returns a list. Default separator is space ‘ ‘. Separator character is ignored, i.e not available in the list. | >>> name=”tanmay singh” >>> name.split(‘n’) [‘ta’, ‘may si’, ‘gh’] >>> message = “Hello dear welcome to mycstutorial.in” >>> message.split() [‘Hello’, ‘dear’, ‘welcome’, ‘to’, ‘mycstutorial.in’] |
partition() | Splits the string at the specified separator, and returns a tuple. Tuple is having only three elements, characters before separator, separator and characters after separator. | >>> name=”tanmay singh” >>> name.partition(‘n’) (‘ta’, ‘n’, ‘may singh’) >>> message = “Hello dear welcome to mycstutorial.in” >>> message.partition(‘ ‘) (‘Hello’, ‘ ‘, ‘dear welcome to mycstutorial.in’) |
join() | Returns a string in which the string elements have been joined by a string separator. Eg. ‘-’.join(‘anjeev” => ‘a-n-j-e-e-v’ | >>> name=”tanmay singh” >>> ‘#’.join(name) ‘t#a#n#m#a#y# #s#i#n#g#h’ >>> “–He–“.join(name) ‘t–He–a–He–n–He–m–He–a–He–y–He– –He–s–He–i–He–n–He–g–He–h’ |
ord(char) | Returns the ordinal value (ASCII) of given character. | >>> ord(‘a’) 97 >>> ord(‘A’) 65 >>> ord(‘#’) 35 |
chr(num) | Returns character represented by inputted ASCII number. | >>> chr(35) ‘#’ >>> chr(65) ‘A’ >>> chr(97) ‘a’ |
Discover more from EduGrown School
Subscribe to get the latest posts sent to your email.