Search

Translate

Strings - python

 You can simply assign a string to a variable by enclosing a character or a word or a sentence with single or double quotes and as the default input data type is a string we can also get string as a input from the user using input() keyword as shown below.

name = 'john' course = "AIML" NAME = input("Enter the name: ")

output:

Enter the name:

here you have to enter the string

Some of the operations performed on strings:

1. upper() - converts whole string into uppercase. 
2. lower() - converts whole string into lower case. 
3. capitalize() - converts the first letter of a string into CAPs. 
4. title() - converts the first letter of every word in a string into Caps. 
5. count() - returns the number of times a specified value occurs in a string. 
6. endswith() - returns True if the string ends with the specified value. 
7. find() - searches for the specified value in a string and returns the position where it was found. 
8. replace() - replaces the specified value with another specified value. 
9. isdigit() - checks whether string is a digit. All the characters should be an digit then only it will return True, even if space is there it will return False.
10. isalpha() - checks whether string is a alphabet. All the characters should be an alphabet then only it will return True, even if space is there it will return False.
11. isalnum() - checks whether string is alpha and numeric. The string should be both an alphabet and numeric.
12. splitlines() - splits the string at line breaks and returns a list.
13. split() - splits the string at the specified separator and returns a list.
14. strip() - Removes the spaces on both sides. You can also specify sides to remove only the space on that side by rstrip or lstrip which removes the space on right or left side respectively.
15. partition() - splits the string into three parts before the specified string, specified string after the specified string.

To make it easy here is the code and their corresponding outputs.
name = 'john is a good boy' print(name.upper())
JOHN IS A GOOD BOY
name = 'AIML' print(name.lower())
aiml
name = 'john is a good boy' print(name.capitalize())
John is a good boy
print(name.title())
John Is A Good Boy
print(name.count('o'))
4
print(name.endswith('boy'))
True
print(name.find('is'))
5
print(name.replace('good','bad'))
john is a bad boy
print(name.isdigit())
False
print(name.isalpha())
False
print(name.isalnum())
False
print(name.split())
['john', 'is', 'a', 'good', 'boy']
name = "john is a good boy. He knows how to behave" print(name.split('.'))
['john is a good boy', ' He knows how to behave']
name = "john is a good boy\n He knows how to behave" print(name.splitlines())
['john is a good boy', ' He knows how to behave']
name = ' AIML ' print(name.strip())
AIML
name = "john is a good boy" print(name.partition('is'))
('john ', 'is', ' a good boy')
Previous
Next Post »