Python Strings
Definition:- String is a sequence of characters or array of character.
Initialization of strings in Python
Characters are placed in single or double quotation marks, for the initialization of string in Python.
Program
Accessing characters of a string
As strings are array of characters, so the elements of string can be accessed by using index numbers.
- Indexing starts with 0.
- First character has an index number of 0, second character has an index number of 1 and soo on.
Accessing an element in a string
Use index to access an element in a string.
Program
String slicing
Provide start index and stop index to slice a string.
Syntax / format:-
string_name[start index : stop index]
Start index:- start the slicing from.
Stop index:- Till where to slice.
Program
>>> st = "This is how you can access"
Slicing starts from the beginning if start index is not specified.
Program
If end index is not specified then string will slice till the end.
Program
>>> st = "This is how you can access"
When both start index and end index is not specified then the whole string is returned.
>>> st = "This is how you can access"
String slicing with intervals
Slice the string by taking specified steps.
Syntax / format:-
string_name[start index : stop index]
Program
>>> st = "This is how you can access"
Steps taken in string by not specifying start index and end index.
Program
'Tssoy ncs'
Length of string
Python built-in function len(), returns the number of characters in a string.
Program
String concatenation
Make use of '+' operator for joining of strings.
Program
Concatenation with more strings.
Program
>>> a = "Hello "
>>> b = "world"
>>> e = "!"
>>> c = a + b + e
>>> print(c)
Hello world!
Strings are immutable
String does not support item assignment.
Program
>>> a = "Hello world"
String placeholders
String formatting can be done in 2 ways.
- Using '%' operator.
- Using format() method
String formatting using modulus operator
Placeholders are placed in the string and the value to be passed into it is defined outside the string.
Program
String formatting with more placeholders.
Program
'Take $30 form John'
For different data types there are different place holders.
For string it's '%s', for integers it's '%d' , for floating point numbers it's '%f' and some more...
Placeholders | Meaning |
---|---|
%d | Integer |
%i | Integer |
%u | Integer |
%f | Float |
%F | Float |
%o | Octave |
%x | Hexadecimal small letters |
%X | Hexadecimal capital letters |
%c | Character, if passed integer then it's corresponding ASCII value is returned |
%s | String |
%r | String placed with single quotation marks |
%e | Exponential small 'e' |
%E | Exponential capital 'E' |
%g | Same as 'e' but, exponent notation is shown when exponential value is less than -4 or greater than 5 |
%G | Same as 'E' but, exponent notation is shown when exponential value is less than -4 or greater than 5 |
String formatting using format() method
Curly braces are used as placeholders, and the value to placed in that placeholders are passed as argument to the format() method.
Program
String formatting with more placeholders.
Program
'Take $35 from John'
It's easy to control the placing of values on to the placeholders, by providing the index of the value that is been passed as argument to the format() method.
Program
One argument value can be placed more number of times in placeholders, with string formatting with format() method.
Program
'Take $35 from this John not that John'
In operator in string
The in operator check if a character or word or phrase is present in the string.
Program
String comparison
Check if two strings are equal.
Returns 'True' if two strings are equal, and 'False' if they are not equal.
Program
All string methods
Here are all the built-in methods available with string.
Methods | Meaning |
---|---|
capitalize() | Makes the first character upper case |
casefold() | Converts string to lower case |
center() | Return a centered string |
count() | Total number of occurrences of substring in string |
encode() | Encodes the string |
endswith() | Returns True if string ends with the specified substring |
expandtabs() | Resize the tab |
find() | Returns lowest index of substring in a string |
format() | Return formatted version of the string using args and kwargs |
format_map() | Returns formatted version of string using mapping |
index() | Returns the lowest index of substring in a string |
isalnum() | Returns True if all the characters are numbers (0-9) |
isalpha() | Returns True if all the characters are alphabet (a-z) and (A-Z) |
isascii() | Returns True if all the characters in string are ASCII, |
isdecimal() | Returns True if all the characters are decimals (Unicode) |
isdigit() | Returns True if all the characters are digits |
isidentifier() | Returns True if the string is valid Python identifier |
islower() | Returns True if all the characters in a string are lower case |
isnumeric() | Returns True if all the characters are numbers. |
isprintable() | Returns True if all the characters in a string are printable |
isspace() | Returns True if full string is whitespace, no other char... |
istitle() | Returns True if first letter of each word in a string is upper case. |
isupper() | Returns True if all the characters in a string are upper cased |
join() | Joins the values specified in iterable with a string specified as separator |
ljust() | Align the string at left by adding characters at the right |
lower() | Converts all the alphabets to lower case letters |
lstrip() | Removes the leading whitespace |
maketrans() | Modifies the characters of a string, by replacing or removing |
partition() | Finds specified separator and return 3-tuple 1. String before separator 2. Separator 3. String after separator |
removeprefix() | Removes the characters specified if it is at the beginning of a string |
removesuffix() | Removes the characters specified if it is present at the end of the string |
replace() | Old substring replaced by new |
rfind() | Find the index of substring occurring at the last Returns -1 on failure |
rindex() | Find the index of substring occurring at the last Raises ValueError on failure |
rjust() | Align the string at right by adding characters at the left |
rpartition() | Finds last specified separator and return 3-tuple 1. String before separator 2. last Separator 3. String after separator |
rsplit() | Returns a list in which each element is a word of a string, and the words are separated by the characters specified |
rstrip() | Removes the specified characters from the end of the string |
split() | same as rsplit, but in rsplit we can specify the maximum number of splits but, in this method we can't |
splitlines() | Returns a list of strings, splitting is done with line breaks '\n'(new line). |
startswith() | Returns Ture if string starts with the specified characters |
strip() | Removes all specified characters from the string |
swapcase() | Converts uppercase to lowercase and lowercase to uppercase |
title() | Returns a string in which first letter of each word is uppercased |
translate() | Replace each character in a string by the specified mapping table |
upper() | Converts all the characters to upper case |
zfill() | Adds '0' at the beginning of the string with specified width |
Conclusion
String is sequence of characters or array of character.
Sentences are placed in single or double quotation marks, for the creation of a string.
Here we learned initialization of a string, accessing characters, accessing string in a range, string slicing, string formatting and the methods available with the string.
Post a Comment
If you have any query, feel free to ask.