2 min to read
Strings
Strings in Python represent unicode characters & are actually an array of bytes
Strings are defined using single or double quotes.
eg: "DevHoot" or 'DevHoot'
Strings in Python represent unicode characters & are actually an array of bytes.
There’s no character type in Python. A single character is represented as a string with a single element.
Elements of of a string are accessed via square brackets [].
Note: Indexing starts at 0
Task: Print the 6th character in the string s
String manipulation
Substring
We can select a part of a given string based on range of indices.
Say we have a string a="Tomato. And we want to select the substring "mat".
We do this by a[2:5]. Here the substring starting from index 2 and ending at index 4(5-1) is selected.
Note: the upper bound is not included.
Task: print elements from 0 to 7 in the given string
Strip whitespaces
The strip() removes any whitespace characters around the beginning & end of the string.
String length
len() function is used to find out the length of a string.
lowercase
Convert a string to lower case using the lower() method.
uppercase
Convert a string to upper case using the upper() method.
Replace part of a string with another string
This is achieved by the replace() method.
Split strings
We can split a string to generate an array of strings. The strings will be split bhy the character we define as the separator.
eg: "hello world".split(" ")
this will split the string by the space and result in an array of two strings ["hello", "world"]
User Input
We can input from the CLI using the input() function.
Comments