Strings in Python

Strings are important in Python. Python has no character type. Hence characters are expressed as strings of length 1. Strings are expressed in single quotes or double quotes. Both are the same in Python. 

Screenshot (18)

String literals can span across multiple lines. One way is using triple-quotes: """...""" or '''...'''.

Screenshot (19)

Strings can be concatenated  with the + operator, and repeated with *:

Screenshot (20)

Two or more strings next to each other are automatically concatenated.

Screenshot (23)

If you want to concatenate variables or a variable and a literal, use + :

screenshot-24.png

Strings are indexed. This mean each character in a string is given an index with respect to its position in the string. The first character has index 0. Indices may also be negative numbers. In that case counting starts from right. This image below must give you a clear depiction of how strings are indexed.

screenshot-22-e1511316024987.png

Slicing in Python gives you substrings.

screenshot-25-e1511316347627.png

Assigning  a character to an index in a string is not valid in Python.

The function len( ) returns the length of a string:

Screenshot (26)

Strings can be converted to uppercase or lowercase.

Screenshot (27)

There are boolean methods to check if the string is alphanumeric,alphabetic,is in lowercase, or in uppercase,etc

The str.join( ),str.split( ),str.replace( ) are also used to manipulate strings in Python. Lets see how they are used. The str.join( ) method returns a string after joining a set of string elements by a particular parameter . The str.split( ) method returns a list of strings that are separated by whitespace if no other parameter is given or if a parameter is specified it separates the string by that particular character. The str.replace( ) method can take a string and return a new string after replacing.

screenshot-28.png

screenshot-283-e1511318718713.png

screenshot-284-e1514667818387.png

screenshot-286.png

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: