Posts

Showing posts with the label string

Generating Random Alphabet in Python

There are two ways to generate a random alphabet in python. The first method uses string and random modules. import string import random randomAlphabet = random.choice(string.ascii_letters) print(randomAlphabet) The second method uses random module only. import random randomCharacter = chr(random.randint(ord("a"), ord("z"))) print(randomCharacter)

.find() and .index() string methods in Python

 The difference between these two methods is that .index()  method raises error while the other does not. str1 = "My name is Abdur." print(str1.find("is")) # gives index of first character occurence print(str1.find("iss")) #does not raises error, returns -1 print(str1.index("is")) # gives index of first character occurence print(str1.index("iss")) # raises error

Reverse a string in Python

A method to reverse a string; stri = "abdur" revStr = stri[::-1] print(revStr)