Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

String Methods in Python

String Methods in Python

String Methods in Python

Python provides a wide variety of built-in string methods to manipulate, search, and modify string values. Below is a list of common string methods and their descriptions.


1. Case Methods

  • lower(): Converts all characters in the string to lowercase.

    s = "HELLO"print(s.lower())  # Output: "hello"
  • upper(): Converts all characters in the string to uppercase.

    s = "hello"print(s.upper())  # Output: "HELLO"
  • capitalize(): Capitalizes the first character of the string and makes all other characters lowercase.

    s = "hello world"print(s.capitalize())  # Output: "Hello world"
  • title(): Capitalizes the first character of each word.

    s = "hello world"print(s.title())  # Output: "Hello World"
  • swapcase(): Swaps the case of each character (lowercase becomes uppercase and vice versa).

    s = "Hello World"print(s.swapcase())  # Output: "hELLO wORLD"
  • casefold(): Similar to lower(), but it’s more aggressive and designed for case-insensitive comparisons (especially useful for comparisons involving non-English characters).

    s = "HELLO"print(s.casefold())  # Output: "hello"

2. Searching Methods

  • find(sub): Returns the index of the first occurrence of sub in the string. Returns -1 if sub is not found.

    s = "hello world"print(s.find("world"))  # Output: 6print(s.find("Python"))  # Output: -1
  • rfind(sub): Returns the index of the last occurrence of sub in the string. Returns -1 if sub is not found.

    s = "hello world, hello"print(s.rfind("hello"))  # Output: 13
  • index(sub): Similar to find(), but raises a ValueError if sub is not found.

    s = "hello world"print(s.index("world"))  # Output: 6# print(s.index("Python"))  # Raises ValueError
  • count(sub): Returns the number of occurrences of sub in the string.

    s = "hello hello world"print(s.count("hello"))  # Output: 2
  • startswith(prefix): Returns True if the string starts with prefix, otherwise False.

    s = "hello world"print(s.startswith("hello"))  # Output: True
  • endswith(suffix): Returns True if the string ends with suffix, otherwise False.

    s = "hello world"print(s.endswith("world"))  # Output: True

3. Trimming Methods

  • strip(): Removes leading and trailing whitespace characters (spaces, tabs, newlines).

    s = "   hello   "print(s.strip())  # Output: "hello"
  • lstrip(): Removes leading whitespace characters.

    s = "   hello"print(s.lstrip())  # Output: "hello"
  • rstrip(): Removes trailing whitespace characters.

    s = "hello   "print(s.rstrip())  # Output: "hello"

4. Modification Methods

  • replace(old, new): Replaces all occurrences of old with new in the string.

    s = "hello world"print(s.replace("world", "Python"))  # Output: "hello Python"
  • split(sep): Splits the string into a list of substrings based on the separator sep. If no separator is provided, it splits by any whitespace.

    s = "hello world"print(s.split())  # Output: ['hello', 'world']s = "apple,banana,orange"print(s.split(','))  # Output: ['apple', 'banana', 'orange']
  • join(iterable): Joins elements of an iterable (like a list) into a string, using the string as the separator.

    words = ["hello", "world"]print(" ".join(words))  # Output: "hello world"
  • zfill(width): Pads the string with zeroes from the left until the string reaches the specified width.

    s = "42"print(s.zfill(5))  # Output: "00042"
  • rjust(width): Aligns the string to the right by padding it with spaces (or other characters) until it reaches the specified width.

    s = "hello"print(s.rjust(10))  # Output: "     hello"
  • ljust(width): Aligns the string to the left by padding it with spaces (or other characters) until it reaches the specified width.

    s = "hello"print(s.ljust(10))  # Output: "hello     "

5. String Alignment Methods

  • center(width): Centers the string within a field of the specified width by padding it with spaces.

    s = "hello"print(s.center(10))  # Output: "  hello   "
  • expandtabs(tabsize): Replaces all tab characters (\t) with spaces, considering tabsize as the number of spaces per tab.

    s = "hello\tworld"print(s.expandtabs(4))  # Output: "hello   world"

6. Testing Methods

  • isalnum(): Returns True if all characters in the string are alphanumeric (letters or numbers).

    s = "hello123"print(s.isalnum())  # Output: True
  • isalpha(): Returns True if all characters in the string are alphabetic (letters).

    s = "hello"print(s.isalpha())  # Output: True
  • isdigit(): Returns True if all characters in the string are digits.

    s = "12345"print(s.isdigit())  # Output: True
  • isspace(): Returns True if all characters in the string are whitespace.

    s = "    "print(s.isspace())  # Output: True
  • istitle(): Returns True if the string is in title case (first letter of each word is capitalized).

    s = "Hello World"print(s.istitle())  # Output: True
  • isupper(): Returns True if all characters in the string are uppercase.

    s = "HELLO"print(s.isupper())  # Output: True
  • islower(): Returns True if all characters in the string are lowercase.

    s = "hello"print(s.islower())  # Output: True

7. Encoding and Decoding Methods

  • encode(encoding): Returns an encoded version of the string as bytes, using the specified encoding.

    s = "hello"encoded = s.encode("utf-8")print(encoded)  # Output: b'hello'
  • decode(encoding): Converts an encoded byte object back into a string using the specified encoding.

    encoded = b'hello'decoded = encoded.decode("utf-8")print(decoded)  # Output: "hello"

Conclusion

These are some of the most commonly used string methods in Python. They allow you to perform a wide range of tasks such as searching, modifying, trimming, and formatting strings. Understanding and using these methods will help you work efficiently with strings in Python.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql