Python String


Youtube Live session on Tkinter

String is an immutable and iterable object.

Declaring string

Both single and double quotes can be used to declare string.
my_str="Welcome to Python." 
print(my_str)
Output
Welcome to Python.

Python declaring multiline strings and concatenation with displaying chars based on position

Multi line string

We use triple quotes to use more than one line strings in Python.
my_str=""" Welcome to Python. 
There are many functions in Python
There are libraries in Python. """
print(my_str)
Output
 Welcome to Python. 
There are many functions in Python
There are libraries in Python.

Adding strings

my_str1="Welcome to "
my_str2="Python" 
my_str=my_str1+my_str2
print(my_str)
Output
Welcome to Python

Char positions in a String

String is an iterable object.
String positions in Python
my_str='plus2net'
print(my_str[0:]) # plus2net ( full string)
print(my_str[1:3])# lu ( from 1 to before 3)
print(my_str[-1]) # t ( last char )
print(my_str[-3:])# net ( last three char)
print(my_str[int(len(my_str)/2)]) #2 ( middle char )
Using for loop
for i in my_str:
  print(i)
Output
p
l
u
s
2
n
e
t
Python string methods with example for searching, replacing and managing cases of chars

String Methods in Python

capitalize()Change to upper case for the first char
center()Center the string by using filling chars
casefold()Change to lower case for all upper case chars in a string
count()Counting Presence of sub string inside main string
endswith()Checking if string ends with input string
expandtabs()Number of spaces to use in place of tab
find()Case sensitive string search
index()Case sensitive string search
isalnum()Check if all chars are alphanumeric in a string
isalpha()Check if all chars are alphabets in a string
isdecimal()Check if all chars are decimal numbers in a string
isdigit()Check if all chars are digits in a string
isidentifier()Check if the string is identifier
islower()Check if all chars are lower case only
isnumeric()Check if all chars are numeric
isprintable()Check if all chars are printable or not
isspace()Check if all chars are whitespace or not
istitle()Check if all words starts with upper case letters
isupper()Check if all chars are upper case letters
join()Join elements of a iterable object
ljust()Left Justifying the string
lower()Change all upper case to lower case chars
lstrip()Removes space or char from left side of the string
partition()Breaking string by using search word
replace()search and replace string inside a main string
rfind()search from right and returns the position of the matching string
rindex()search from right and returns the position of the matching string
rjust()Right Justify the string
rpartition()Breaking string by using search word from right
rsplit()Breaking string by using delimiter
rstrip()Removing chars from right side
split()Split the string using delimiters
splitlines()Break the string using line breaks
startswith()Check if string is starting with or not
strip()Remove space or char from left or right of the string
swapcase()Change case from lower to upper and upper to lower
title()First char of each word to upper case letter
translate()Mapping chars of a string
upper()Change all lower case to upper case letter
zfill()fill the left of the string with zeros
regular expressionExtracting date from a string

Python string methods to check matching conditions and return True of False ( Boolean )

Common Question

Find out the frequency of occurrence of chars in a string?
my_str='Welcome to Python'
my_dict={}
for i in my_str:
  if i in my_dict:
    my_dict[i] = my_dict[i] + 1
  else:
    my_dict[i]  = 1
print(my_dict)
Output
{'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 3, 'm': 1, ' ': 2,
 't': 2, 'P': 1, 'y': 1, 'h': 1, 'n': 1}
Basic & Advance Questions on String

Return the matching strings from a list

my_list=['aecde','adba','acbd','abcd','abded','bdbd','baba']
search_str='ab'
filtered = [s for s in my_list if search_str in s] 

Using regular expression

We can return matching strings by using search() method of regular expression. We can also use match when we want matching string from starting of the string only ( Not any where match )
import re # regular expression library 
my_list=['aecde','adba','acbd','abcd','abded','bdbd','baba']
search_str='ab' # searh string 
for element in my_list:
    #if(re.search(search_str,element,re.IGNORECASE)):
    if(re.match(search_str,element,re.IGNORECASE)):    
        print(element)
Output using match()
abcd
abded
If we use search() by commenting the match() method and using the search() , output is here
abcd
abded
baba

String between two sub-strings

Here is a variable declared in PHP, we have to collect the value of the variable.
$var1=PY_tkinter_end;
Our ouput should collect the value assigned i.e tkinter
import re

data="$var1=PY_tkinter_end;"
str1 = re.search('PY_(.*)_end', data)
print(str1.group(1)) # tkinter
Here is the original string with escape chars to take care the double quotes. Out final output should read Data within Description
<META NAME=\"DESCRIPTION\" CONTENT=\"Data within Description\">
des = re.search('<META NAME=\\\\"DESCRIPTION\\\\" CONTENT=\\\\"(.*)\\\\">', data)
Python if else for loop
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer