Python – useful string methods

Hi all, here is a brief list of useful string methods.

capitalize(). Makes the first letter of the string uppercase and all the rest lowercase, and returns the result.
lower(). Returns a version of the string with all uppercase letters changed to lowercase.
upper(). Returns a version of the string with all lowercase letters changed to uppercase.
title(). Returns a version of the string with each word (e.g., letter following a space) capitalized.
strip(). Returns a version of the string with any whitespaces (spaces, line breaks, etc.) at the beginning and end of the string removed. rstrip() and lstrip() apply this strip() method only to the right or left sides of the string.
replace(old, new). Replace all occurrences of the substring old with the substring new.
rfind(findString). Just like find(), but returns the last index of findString instead of the first.
join(list). Creates a string where each item in the list is followed by the string, and returns the result.

endswith(suffix). Returns True if the string ends with suffix, False if not.
startswith(prefix). Returns True if the string starts with prefix, False if not.
isalnum(). Returns True if the string is all letters and numbers, False if not.
isalpha(). Returns True if the string is all letters, False if not.
isdecimal(). Returns True if the string represents an integer or decimal number, False if not.
isdigit(). Returns true if the string is all numbers (e.g., represents an integer), False if not. isnumeric() is similar, but supports fraction and other characters as well (which are rarely used).
islower(). Returns True if the string contains no uppercase letters, False if not.
isupper(). Returns True if the string contains no lowercase letters, False if not.
istitle(). Returns True if the string is in title case, meaning each word is capitalized, and False if not.

Here is a sample:

str1 = "this is MY test string!   "
print("Original state: "+"\t\t\t"+str1)
print("with Capitalize method: "+"\t"+str1.capitalize())
print("with Lower method: "+"\t\t\t"+str1.lower())
print("with Upper method: "+"\t\t\t"+str1.upper())
print("with Title method: "+"\t\t\t"+str1.title())
print("with Capitalize method: "+"\t"+str1.capitalize())
print("with Strip method: "+"\t\t\t"+str1.strip())
print("with Replace method: "+"\t\t"+str1.replace("MY","YOUR"))

list1 = str1.split()
print(list1)
new_str1 = "%".join(list1)
print(new_str1.split("s"))

The output will be;
Original state: 			this is MY test string!   
with Capitalize method: 	This is my test string!   
with Lower method: 			this is my test string!   
with Upper method: 			THIS IS MY TEST STRING!   
with Title method: 			This Is My Test String!   
with Capitalize method: 	This is my test string!   
with Strip method: 			this is MY test string!
with Replace method: 		this is YOUR test string!   
['this', 'is', 'MY', 'test', 'string!']
['thi', '%i', '%MY%te', 't%', 'tring!']

Python – Valid character list

Hi, let us check the given string against a valid character list. There might be numerous way to do this. Here is a sample one.

 

str_to_check = "1234-3*33?3+----!"
valid_chars = "0123456789-+"
uyan_char_sayisi = 0
uymayan_listesi = ""
uymayan_char_sayisi = 0

str_to_check_uzunluk = len(str_to_check)
valid_chars_uzunluk = len(valid_chars)
#print(str_to_check_uzunluk)
for i in range(0,str_to_check_uzunluk):
    for j in range(0,valid_chars_uzunluk):
        if str_to_check[i] == valid_chars[j]:
            uyan_char_sayisi += 1
    if not str_to_check[i] in valid_chars:
        uymayan_listesi += str_to_check[i]

if uyan_char_sayisi == str_to_check_uzunluk:
    print("String is valid")
else:
    print("String is invalid")
print("Here is/are the invalid character(s) :",uymayan_listesi)

The output will be;
String is invalid
Here is/are the invalid character(s) : *?!

Python – Average word count 2

Hi, here is a kind of follow up for the 1st one. We, in this exercise , deal with leading space(s) , Boolean and punctuation.

def average_word_length(my_string):
    space_sayisi = 0
    word_sayisi = 0
    letter_sayisi= 0
    ortalam_word_uzunlugu = 0
    punctuation_sayisi = 0
    punctuation_listesi = ".,!? "
    try:
        uzunluk = len(my_string)
    except:
        return "Not a string"
    for i in range(0,uzunluk):
        if my_string[i] in punctuation_listesi:
            punctuation_sayisi += 1
        if punctuation_sayisi == len(my_string):
            return "No word"
        if my_string[i].isspace() and my_string[i+1].isalpha():
            space_sayisi += 1
            #print(space_sayisi)
    if my_string[0].isspace():
        space_sayisi -= 1
    word_sayisi = space_sayisi +1
    for i in range(0,uzunluk):
        if my_string[i].isalpha():
            letter_sayisi += 1
    ortalam_word_uzunlugu = letter_sayisi / word_sayisi
    return ortalam_word_uzunlugu





print(average_word_length("Hi"))
print(average_word_length("Hi, Lucy"))
print(average_word_length("   What   big spaces  you    have!"))
print(average_word_length(True))
print(average_word_length("?!?!?! ... !"))

The output will be;
2.0
3.0
4.0
Not a string
No word

Python – Error Handling 2

Hi all, here are more examples for error handling.

my_value = 10

try:
    print(1 / my_value)
    print("No error occurred!")
except NameError:
    print("A NameError occurred!")
except ZeroDivisionError:
    print("A ZeroDivisionError occurred!")
except TypeError:
    print("A TypeError occurred!")
print("Done!")
We catch three error types.

try:
    print(undeclared_variable)     #---> cause of a NameError
    print(1 / 0)                  #---> cause of a ZeroDivisionError
    print("No error occurred!")
except NameError:
    print("A NameError occurred!")
except ZeroDivisionError:
    print("A ZeroDivisionError occurred!")
print("Done!")

Python – Error Handling 1

Hi all, here are the samples for error handling with try/catch.

my_value = "0"
try:
    print(10 / my_value)

except ZeroDivisionError:
    print("Can't divide by zero")
except:
    print("Not possible")
When you run the code, here is the output
Not possible
my_value = 0
try:
    print(10 / my_value)

except ZeroDivisionError:
    print("Can't divide by zero")
except:
    print("Not possible")
When you rune the code, here is the output
Can't divide by zero
my_value = 5
try:
    print(10 / my_value)

except ZeroDivisionError:
    print("Can't divide by zero")
except:
    print("Not possible")
When you run the code, here is the output
2.0

Python – Average word count

Hi  all, this a function usage sample and it aims to find average word count in a given string.  We call word_count and letter_count functions in average_word_length function. That’s all 🙂

def word_count(a_string):
    space_count = 0
    word_count = 0
    for i in a_string:
        if i == " ":
            space_count = space_count + 1
    word_count = space_count + 1
    return word_count


def letter_count(a_string):
    letter_count = 0
    for i in a_string:
        if i.isalpha() or i != " ":
            letter_count += 1
    return letter_count


def average_word_length(a_string):
    average_word_length = 0
    harf_sayisi = letter_count(a_string)
    kelime_sayisi = word_count(a_string)
    average_word_length = harf_sayisi/kelime_sayisi
    return average_word_length

a_string = "Up with the black and silver"
print(average_word_length(a_string))
print("kelime sayisi",word_count(a_string))
print("harf sayisi",letter_count(a_string))

The output should be 3.8333333333333335

Python – get current date

Hi, here is a sample for getting current date and print it. There are various string formating that you can choose regarding to your needs.

In order to drop the leading zero (01/09/2018 > 1/9/2018) you can apply “-” or “#”. I added a comment for this.

from datetime import date
#gun=date.today()
#gun1=gun.strftime("%Y/%m/%d")
#print(gun.strftime("%Y/%m/%d"))
#print(gun1)
def get_todays_date():
    gun = date.today()
    gun1 = gun.strftime("%Y/%#m/%#d")  #windows pc'lerde # , linux vb. de # yerine -
    return gun1
print(get_todays_date())

Python – Let’s count a word in a string

Hi, I guess this is not the best practice but it works 🙂

Let’s count “cat” in a given string.

mystery_string = "why cat wy dog cat cacacat cacacat o cat bye cat cat"
uzunluk_my_string = len(mystery_string)
cat_sayisi = 0
#print(uzunluk_my_string)
for i in range(0,uzunluk_my_string):
    #print(i)
    if mystery_string[i] == "c":
        #print(i," ",mystery_string[i])
        if mystery_string[i+1] == "a":
            if mystery_string[i+2] == "t":
                cat_sayisi = cat_sayisi + 1
                #print(cat_sayisi)
            #else:
                #break
        #else:
            #break

print(cat_sayisi)

# The output is 7

Python- multiplication / time table

Hi, here is a time table code for a given value. The tricky part is the 2nd print() function. It starts a new line.

my_int = 5
for i in range(1,my_int+1):
    for j in range(1,my_int+1):
        print(i*j,end= "\t")
    print()
#The output is shown below
1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

You can add some formatting as shown below
my_int = 5
for i in range(1,my_int+1):
    for j in range(1,my_int+1):
        print("{:5}".format(i*j),end= "\t")
    print()
#The output is shown below
    1	    2	    3	    4	    5	
    2	    4	    6	    8	   10	
    3	    6	    9	   12	   15	
    4	    8	   12	   16	   20	
    5	   10	   15	   20	   25	

Python – ord() and chr() functions

Hi, these functions, for example , convert a letter into its corresponding ascii code and vice versa.

ord(A) –> give the value of 65

chr(65) –> would give “A”

Here is a sample code for printing the alphabet 🙂

start_character = "A"
end_character = "Z"
for i in range(ord(start_character),ord(end_character)+1):
    print(chr(i))