Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In Python, you can easily convert strings to upper or lower case using built-in string methods. The lower()
method converts a string to lowercase, while the upper()
method converts a string to uppercase.
lower()
method:The lower()
method returns a new string with all the characters in the original string converted to lowercase. Here's an example:
text = "Hello, World!" lowercase_text = text.lower() print(lowercase_text) # Output: hello, world!
upper()
method:The upper()
method returns a new string with all the characters in the original string converted to uppercase. Here's an example:
text = "Hello, World!" uppercase_text = text.upper() print(uppercase_text) # Output: HELLO, WORLD!
These methods are useful for case-insensitive comparisons or text normalization, as they can ensure that strings have a consistent case before performing operations on them.
For example, when comparing user input without considering case differences, you can convert both the input and the comparison string to lowercase:
user_input = "Yes" if user_input.lower() == "yes": print("User agreed.") else: print("User disagreed.")
In this example, the comparison will be true whether the user types "yes", "Yes", "YES", or any other combination of upper and lowercase characters.
Converting string to lowercase in Python:
original_string = "Hello World" lowercase_string = original_string.lower()
Using the lower() method in Python strings:
lower()
method is used to convert a string to lowercase.original_string = "Hello World" lowercase_string = original_string.lower()
String case manipulation in Python:
lower()
, upper()
, and title()
.original_string = "Hello World" lowercase_string = original_string.lower() uppercase_string = original_string.upper() title_case_string = original_string.title()
Changing string to uppercase in Python:
original_string = "Hello World" uppercase_string = original_string.upper()
Using the upper() method for uppercase strings in Python:
upper()
method converts a string to uppercase.original_string = "Hello World" uppercase_string = original_string.upper()
Title case conversion in Python strings:
original_string = "hello world" title_case_string = original_string.title()
Python case-insensitive string comparison:
casefold()
or lower()
.string1 = "Hello" string2 = "hello" is_equal = string1.casefold() == string2.casefold()
Conditional case conversion in Python strings:
original_string = "Hello World" condition = True modified_string = original_string.lower() if condition else original_string.upper()