Sunday, August 19, 2018

Python String and String Manipulating Functions


String literals in Python programming language are surrounded by either single quotation marks, or double quotation marks.

Both 'hello' and "hello" are same.

Strings can be output to screen using the print function. For example: print("hello").

Like other programming languages, Python string index starts from 0, means first character of the string can be accessed using 0 index.

s1 = "Hello, World!"
print(s1[1]) will display 'e'

Again substring of a string can be extracted using the statement: str1 = "Hello, World!"
print(str1[2:5]) It will extract characters from index 2 to index 5

strip () function

To trim leading and trailing whitespaces from a string, use strip () function.

str1 = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

len () function

To find the length of a string, len () method is used. The len () function takes the string as argument. Str1 = "Hello, World!"
print(len(str1))


lower () and upper () function


The lower() method returns the string in lower case while upper () function returns the upper case version of the string. Both the functions are invoked using the string. Return type of both the functions are string.

str1 = "Hello, World!"
print(str1.lower())


str1 = "Hello, World!"
print(str1.upper())


replace () function

The replace() method replaces a string with another string:

str1 = "Hello, World!"
print(str1.replace("Hello", "Hi"))

The output would be Hi, World

split() function

The split() method splits the string into substrings depending on the separator passed as argument as string.

str1 = "Hello, World!"
print(str1.split(",")) # returns ['Hello', ' World!']


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner