Members

A succession of characters is referred to as a string. A character is nothing more than a symbol. The English language, for example, has 26 characters.

Numbers are what computers work with, not characters (binary). Although you may see characters on your screen, they are stored and modified inside as a series of 0s and 1s.
Encoding is the process of converting a character to a number, and decoding is the reverse procedure. Some of the most often used encodings include ASCII and Unicode.

A string in Python is a collection of Unicode characters. Unicode was created to encompass all characters in all languages and offer encoding standardization. Python Unicode is a good place to start learning about Unicode.

In Python, how do you make a string?
Strings are formed by enclosing characters within single or double quotations. In Python, triple quotes can be used to represent multiline strings and docstrings, but they are most commonly used to represent multiline strings and docstrings.

# defining strings in Python
# all of the following are equivalent
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)

How can I get a list of characters in a string?
Indexing allows us to access individual characters, while slicing allows us to access a group of characters. The index begins at zero. If you try to access a character outside of the index range, you'll get an IndexError. An integer must be used as the index. We can't use floating or other kinds because TypeError will occur.

Python sequences support negative indexing.

The last item is represented by the index -1, the second last item by the index -2, and so on. Using the slicing operator, we can get a list of things in a string: (colon).

#Accessing string characters in Python
str = 'program'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])

Strings are one of the most commonly used data types in Python since they can execute a wide range of operations. Also, learn how to convert Int to String in Python.

Views: 5

Comment

You need to be a member of On Feet Nation to add comments!

Join On Feet Nation

© 2024   Created by PH the vintage.   Powered by

Badges  |  Report an Issue  |  Terms of Service