Skip to main content

String Methods

In Python, strings are like text containers that come with their own set of useful tools. These tools, called string methods, allow you to modify and work with strings in different ways. Here are some commonly used string methods and what they do:

1. `capitalize()`: Makes the first letter of a string uppercase and the rest lowercase.

2. `casefold()`: Converts the entire string to lowercase, even handling special cases.

3. `center(width[, fillchar])`: Puts a string in the middle of a line of a specific width, optionally filling the extra space with a chosen character.

4. `count(sub[, start[, end]])`: Counts how many times a specific part of a string appears within it.

5. `endswith(suffix[, start[, end]])`: Checks if a string ends with a particular set of characters and returns True or False.

6. `find(sub[, start[, end]])`: Searches for a specific part of a string and tells you where it starts. If not found, it returns -1.

7. `index(sub[, start[, end]])`: Similar to `find()`, but if the substring is not found, it raises an error instead of returning -1.

8. `isalnum()`: Checks if all characters in a string are either letters or numbers.

9. `isalpha()`: Checks if all characters in a string are letters.

10. `isdigit()`: Checks if all characters in a string are digits (numbers).

11. `islower()`: Checks if all characters in a string are lowercase.

12. `isspace()`: Checks if all characters in a string are whitespace (spaces, tabs, etc.).

13. `isupper()`: Checks if all characters in a string are uppercase.

14. `join(iterable)`: Joins together multiple strings from a list or other iterable, using the string as a connector.

15. `len()`: Gives you the length (number of characters) of a string.

16. `lower()`: Converts all characters in a string to lowercase.

17. `lstrip([chars])`: Removes any leading whitespace (spaces, tabs) or specified characters from the left side of a string.

18. `replace(old, new[, count])`: Replaces all occurrences of a specific part of a string with another part.

19. `split([sep[, maxsplit]])`: Breaks a string into multiple parts based on a specified separator.

20. `startswith(prefix[, start[, end]])`: Checks if a string starts with a specific set of characters and returns True or False.

21. `strip([chars])`: Removes any leading or trailing whitespace or specified characters from a string.

22. `swapcase()`: Changes the case of all characters in a string, swapping uppercase to lowercase and vice versa.

23. `title()`: Makes the first letter of each word in a string uppercase and the rest lowercase.

24. `upper()`: Converts all characters in a string to uppercase.

These methods offer great flexibility when working with strings in Python. Feel free to explore and experiment with them to make your string manipulation tasks easier!


What is the __str __ function in Python?

The `__str__` function in Python is a special method that allows you to define how an object should be represented as a string. When you use the `print()` function or the `str()` function on an object, Python will call the `__str__` method on that object to get a string representation of it. By default, if you try to print an object that doesn't have a `__str__` method defined, Python will print the object's memory location instead, which is not very useful for humans to read. To define the `__str__` method for your own custom classes, you simply need to include a method with that name in your class definition. For example: ```python class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} is {self.age} years old." ``` In this example, we define a `Person` class with a `name` and an `age` attribute. We also define a `__str__` method that returns a string representation of a `Person` object. Now, if we create a `Person` object and try to print it, we'll get a more useful string representation: ```python >>> person = Person("Alice", 25) >>> print(person) Alice is 25 years old. ``` By defining the `__str__` method, we can customize how our objects are represented as strings and make them more readable and informative for humans.



Comments

Labels

Show more

Popular post

Python - Output Variables

Output variables in Python refers to the process of displaying or printing the value of a variable to the console or output stream. This is a crucial aspect of programming as it allows developers to test and debug their code and also helps users to interact with the program. In Python, we can output variables to the console using the print() function. The syntax for using the print() function is straightforward: ``` variable_name = "Hello, World!" print(variable_name) ``` In this example, we have created a variable called `variable_name` and assigned it the value "Hello, World!". We then use the print() function to output the value of `variable_name` to the console. We can also output multiple variables using the print() function by separating them with commas. For example: ``` name = "John" age = 25 print("My name is", name, "and I am", age, "years old.") ``` In this example, we have created two variables called `name` and `a...

Python - Global Variables

In Python, a global variable is a variable that is declared outside of any function and can be accessed by any function in the same module or file. Global variables can be useful for storing values that are needed by multiple functions within the same module or file. In Python, declaring a variable outside of any function is all that's needed to create a global variable: ``` # defining a global variable my_global_var = "Hello World" # Creating a function that utilizes the global variable: def print_global_var():     print(my_global_var) # calling the function print_global_var()  # output: "Hello World" ``` In the example above, `my_global_var` is a global variable that can be accessed by the function `print_global_var()` because it is defined outside of any function. It is also possible to modify the value of a global variable from within a function using the `global` keyword: ``` # defining a global variable my_global_var = "Hello World" # defining a ...

Legal drinking age around the world

From hard liquor to hard seltzer, alcoholic beverages are an almost ubiquitous part of many modern cultures: wine with dinner, beer with friends on the weekend, celebratory champagne toasts, etc. However, because alcohol is a drug that can significantly affect a person's judgment and physical abilities, many countries age-restrict the consumption of alcoholic beverages. Effects of alcohol on the body In chemical terms, alcohol is an organic compound produced when grains, vegetables or fruits are allowed to ferment. Medically, alcohol is classified as a depressant (as opposed to stimulants like caffeine or hallucinogens like psilocybin) with a wide range of physiological effects. Most of these effects involve a reduction or inhibition of physical activity. For example, alcohol inhibits physical motor function and slows reaction time. Consequently, the more one drinks, the slower and more sluggish one becomes. Similarly, alcohol also inhibits the brain's communication pathways. T...