Python Strings: Manipulating and Formatting Text


Python strings are used to store and manipulate text. They are sequences of characters enclosed in single or double quotes. For example:

string1 = "Hello, World!" string2 = 'This is a string.'

You can access individual characters in a string using indexing. The index of the first character is 0, and the index of the last character is -1. For example:

first_char = string1[0] # Output: "H" last_char = string1[-1] # Output: "!"

You can also access a range of characters in a string using slicing. The syntax for slicing is [start:end:step]. The start index is the index of the first character, the end index is the index of the character after the last character, and the step is the number of indices between each character. The default values for start, end, and step are 0, the length of the string, and 1, respectively. For example:

substring = string1[2:5] # Output: "llo"

You can also use slicing to reverse a string. To do this, you can set the step value to -1. For example:

reversed_string = string1[::-1] # Output: "!dlroW ,olleH"

To concatenate strings, you can use the + operator. For example:

string3 = string1 + string2 # Output: "Hello, World!This is a string."

To repeat a string, you can use the * operator. For example:

string4 = string1 * 3 # Output: "Hello, World!Hello, World!Hello, World!"

To check if a string contains a certain substring, you can use the in operator. For example:

if "World" in string1: print("Yes, the string contains the substring 'World'.") else: print("No, the string does not contain the substring 'World'.") # Output: "Yes, the string contains the substring 'World'."

To find the length of a string, you can use the len() function. For example:

string_length = len(string1) # Output: 13

To convert a string to uppercase or lowercase, you can use the upper() and lower() methods, respectively. For example:

string1_upper = string1.upper() string2_lower = string2.lower() print(string1_upper) # Output: "HELLO, WORLD!" print(string2_lower) # Output: "this is a string."

To remove leading and trailing whitespace from a string, you can use the strip() method. For example:

string5 = " This string has leading and trailing whitespace. " stripped_string = string5.strip() print(stripped_string) # Output: "This string has leading and trailing whitespace."

To split a string into a list of substrings, you can use the split() method. The split() method takes a separator as an argument, and returns a list of substrings separated by the separator

Comments