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.

Strings in Python

Strings in Python

Strings in Python

In Python, a string is a sequence of characters enclosed within single quotes (') or double quotes ("). Strings are used to represent textual data and are one of the most commonly used data types in Python.


Creating Strings

  1. Single Quotes:

    s = 'Hello, World!'
  2. Double Quotes:

    s = "Hello, World!"
  3. Triple Quotes (used for multi-line strings):

    • Triple single quotes (''') or triple double quotes (""") are used for creating multi-line strings.

    s = '''This isa multi-linestring.'''
  4. Escape Characters:
    To include special characters like quotes or newlines within a string, you can use escape sequences (preceding the character with a backslash \).

    s = "He said, \"Hello!\""print(s)  # Output: He said, "Hello!"

String Indexing

Python strings are indexed sequences. The index starts from 0 for the first character.

s = "Hello"print(s[0])  # Output: 'H' (first character)print(s[1])  # Output: 'e' (second character)print(s[-1]) # Output: 'o' (last character)
  • Positive indexing starts from 0 to the length of the string.

  • Negative indexing starts from -1 for the last character, -2 for the second last character, and so on.


String Slicing

Slicing allows you to extract a substring from a string. The syntax is:
string[start:end:step]

  • start: The starting index (inclusive).

  • end: The ending index (exclusive).

  • step: The interval (optional).

s = "Hello, World!"# Extracting substringprint(s[0:5])    # Output: 'Hello'print(s[7:])     # Output: 'World!'print(s[:5])     # Output: 'Hello'print(s[::2])    # Output: 'Hoo ol!'
  • Negative Indices:

    s = "Hello, World!"print(s[-6:-1])  # Output: 'World'

String Concatenation

You can combine multiple strings using the + operator.

s1 = "Hello"s2 = "World"s3 = s1 + " " + s2print(s3)  # Output: 'Hello World'

String Repetition

You can repeat a string using the * operator.

s = "Hello"print(s * 3)  # Output: 'HelloHelloHello'

String Length

To get the length of a string, you can use the built-in len() function.

s = "Hello, World!"print(len(s))  # Output: 13

String Immutability

Strings in Python are immutable, meaning that once a string is created, you cannot change its individual characters.

s = "Hello"# The following will raise an error# s[0] = "h"  # TypeError: 'str' object does not support item assignment

However, you can create a new string based on modifications to an existing string.

s = "Hello"s = "h" + s[1:]print(s)  # Output: 'hello'

String Methods

Python provides a variety of string methods that can be used to manipulate or query strings. Here are some of the most commonly used string methods:

1. String Case Methods

  • lower(): Converts the string to lowercase.

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

    s = "hello"print(s.upper())  # Output: 'HELLO'
  • capitalize(): Capitalizes the first character of the string.

    s = "hello"print(s.capitalize())  # Output: 'Hello'

2. Searching Methods

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

    s = "Hello, World!"print(s.find("World"))  # Output: 7
  • count(sub): Returns the number of occurrences of sub in the string.

    s = "Hello, World!"print(s.count("o"))  # Output: 2

3. String Trimming

  • strip(): Removes leading and trailing whitespaces from the string.

    s = "   Hello, World!   "print(s.strip())  # Output: 'Hello, World!'
  • lstrip(): Removes leading whitespace.

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

    s = "Hello   "print(s.rstrip())  # Output: 'Hello'

4. String Replacement

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

    s = "Hello, World!"print(s.replace("World", "Python"))  # Output: 'Hello, Python!'

5. String Splitting and Joining

  • split(sep): Splits the string into a list of substrings based on the separator sep.

    s = "Hello, World!"print(s.split(", "))  # Output: ['Hello', 'World!']
  • join(iterable): Joins elements of an iterable (e.g., a list) into a string, separated by the string itself.

    words = ["Hello", "World"]print(" ".join(words))  # Output: 'Hello World'

Conclusion

Strings are a fundamental part of Python, and understanding how to manipulate and work with them is essential. With Python’s built-in methods, you can easily perform a variety of operations on strings, such as searching, trimming, replacing, and formatting. These methods give you the flexibility to work with strings efficiently.

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