Programming Tutorials

python string

By: Ashley J in Python Tutorials on 2017-09-27  

Python String objects (byte strings, as well as text, AKA Unicode, ones) are immutable: attempting to rebind or delete an item or slice of a string will raise an exception. The items of a string object (corresponding to each of the characters in the string) are themselves strings of the same kind, each of length 1. 

Unicode str and bytes objects are immutable sequences. All immutable-sequence operations (repetition, concatenation, indexing, and slicing) apply to them, returning an object of the same type. Listed below are some methods available for string handling in Python.

Here are some common string operations in Python:

  1. Concatenation: You can concatenate two or more strings using the + operator. For example:
    str1 = "Hello"
    str2 = "World"
    str3 = str1 + " " + str2
    print(str3) # Output: "Hello World"
    
  2. Length: You can get the length of a string using the len() function. For example:
    str = "Hello World"
    print(len(str)) # Output: 11
    
  3. Indexing and Slicing: You can access individual characters of a string using indexing, and a range of characters using slicing. For example:
    str = "Hello World"
    print(str[0]) # Output: "H"
    print(str[6:11]) # Output: "World"
    
  4. Case Conversion: You can convert the case of a string using the upper() and lower() methods. For example:
    str = "Hello World"
    print(str.upper()) # Output: "HELLO WORLD"
    print(str.lower()) # Output: "hello world"
    
  5. String Replacement: You can replace a substring within a string using the replace() method. For example:
    str = "Hello World"
    new_str = str.replace("World", "Python")
    print(new_str) # Output: "Hello Python"
    
  6. String Formatting: You can format a string using placeholders {} and the format() method. For example:
    name = "Alice"
    age = 30
    print("My name is {} and I am {} years old.".format(name, age))
    # Output: "My name is Alice and I am 30 years old."
    

These are just a few of the many string operations available in Python.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)