Code Pumpkin

Strings in Python

October 26, 2018
Posted by Dipen Adroja

We have seen some of the datatypes till now. In this Article, we will explore more about String datatype in python. Strings are amongst the most popular types in Python. String object can be created by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable as shown below:

var1 = 'Hello World!'

var2 = "Python Programming"

Various String Operators

There are various string operators that can be used in different ways like concatenating a different string.

Assume string variable a holds ‘Code’ and variable b holds 'Pumpkin’, then −

 Operator

 Description

 Example

 +

 Concatenation of two string

 a + b will give HelloPython

 not in 

 Returns true if character exist in given String

 M not in a will give 1

 *

 Repetition – Creates new strings, concatenating multiple copies of the same string

 a*2 will give -CodeCode

 in

 Returns true if a character exists in given string

 C in a will give 1

 %

 Format – Performs String formatting

 See at next section

 [ : ]

 Returns character in given range

 a[1:4] will give ode

 []

 Slice – Gives the character from the given index range

 a[1] will give o

String Formatting Operator

One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. As shown below:

String Example

Here is the list of the complete set of symbols which can be used along with % −

Format Symbol

Conversion

 %c

 character 

 %s

 string conversion via str() prior to formatting

 %i

 signed decimal integer

 %d

 signed decimal integer

 %u

 unsigned decimal integer

 %o

 octal integer

 %x

 hexadecimal integer (lowercase letters)

 %X

 hexadecimal integer (UPPERcase letters)

 %e

 exponential notation (with lowercase 'e')

 %E

 exponential notation (with UPPERcase 'E')

 %f

 floating point real number

 %g

 the shorter of %f and %e

 %G

 the shorter of %f and %E

Triple Quotes

Python's triple quotes allow strings to span multiple lines, including TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.


#!/usr/bin/python

demo_str = ‘’’This is a demo string for showing multiline string.
This is second line and this will be printed on second line. Other special characters newline \n and tabs (\t) can also be used with in’’’

print(demo_str)

When the above code is executed, it produces the following result.

Multiline strings

Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n)

Python string methods:

Python comes with some built-in functions to manipulate strings. Some of the methods are listed below with its description.

Python String Methods

Example

capitalize() – Returns the string with first letter capitalized and the rest lowercased.

string = “codepumpkin is awesome."

capitalized_string = string.capitalize()

print('Old String: ', string)

print('Capitalized String:', capitalized_string)

Output:

Old String:  codepumpkin is awesome.

Capitalized String: Codepumpkin is awesome.

casefold() – Returns a lowercase string, generally used for caseless matching. This is more aggressive than the lower() method.

string = "CODEPUMPKIN IS AWESOME"

# print lowercase string

print("Lowercase string:", string.casefold())

Output:

Lowercase string: codepumpkin is awesome

center() – Center the string within the specified width with optional fill character.

string = "Codepumpkin is awesome"

new_string = string.center(24, *)

print("Centered String: ", new_string)

Output:

Centered String:    ***Codepumpkin is awesome****

count() – Count the non-overlapping occurrence of supplied substring in the string.

# define string

string = "Codepumpkin is awesome, isn't it?"

substring = "i"

count = string.count(substring, 9, 24)

print("The count is:", count)

Output:

The count is: 1

encode() – Return the encoded version of the string as a bytes object.

# unicode string

string = 'cödepumpkin!'

print('The string is:', string)

# default encoding to utf-8

string_utf = string.encode()

print('The encoded version is:', string_utf)

Outout:

The string is: pythön!

The encoded version is: b’c\xc3\xb6depumpkin!’

endswith() – Returns ture if the string ends with the supplied substring.

text = "Python is easy to learn."

result = text.endswith('to learn')

# returns False

print(result)

result = text.endswith('to learn.')

# returns True

print(result)

expandtabs() – Return a string where all the tab characters are replaced by the supplied number of spaces.

str = 'xyz\t12345\tabc'

# no argument is passed

# default tabsize is 8

result = str.expandtabs()

print(result)

Output:

xyz     12345   abc

find() – Return the index of the first occurrence of supplied substring in the string. Return -1 if not found.

quote = 'Let it be, let it be, let it be'

result = quote.find('let it')

print("Substring 'let it':", result)

Output:

Substring 'let it': 11

format() – Format the given string.

# default arguments

print("Hello {}, your balance is {}.".format("Adam", 230.2346))

Output:

Hello Adam, your balance is 230.2346.

format_map() – Format the given string.

point = {'x':4,'y':-5}

print('{x} {y}’.format_map(point))

Output:

4 -5

index() – Return the index of the first occurrence of supplied substring in the string. Raise ValueError if not found.

sentence = 'Python programming is fun.'

result = sentence.index('is fun')

print("Substring 'is fun':", result)

Output:

Substring 'is fun': 19

isalnum() – Return true if the string is non-empty and all characters are alphanumeric.

All this boolean method returns true or false

isalpha() – Return true if the string is non-empty and all characters are alphabetic.

  

isdecimal() – Return true if the string is non-empty and all characters are decimal characters.

isdigit() – Return true if the string is non-empty and all characters are digits.

isidentifier() – Return true if the string is a valid identifier.

islower() – Return true if the string has all lowercased characters and at least one is cased character.

isnumeric() – Return true if the string is non-empty and all characters are numeric.

isprintable() – Return true if the string is empty or all characters are printable.

isspace() – Return true if the string is non-empty and all characters are whitespaces.

istitle() – Return true if the string is non-empty and titlecased.

isupper() – Return true if the string has all uppercased characters and at least one is cased character.

join() – Concatenate strings in the provided iterable with separator between them being the string providing this method.

numList = [‘1’, ‘2’, ‘3’, ‘4’]

seperator = ', '

print(seperator.join(numList))

Output:

1, 2, 3, 4

ljust() – Left justify the string in the provided width with optional fill characters.

string.ljust(width[, fillchar])

lower() – Return a copy of all lowercased string.

string.lower()

lstrip() – Return a string with provided leading characters removed.

string.lstrip([chars])

maketrans() – Return a translation table.

string.maketrans(x[, y[, z]])

partition() – Partition the string at first occurrence of substring (separator) and return a 3-tuple with part before separator, the separator and part after separator.

string.partition(separator)

replace() – Replace all old substrings with new substrings.

str.replace(old, new [, count])

rfind() – Return the index of the last occurrence of supplied substring in the string. Return -1 if not found.

str.rfind(sub[, start[, end]] )

rindex() – Return the index of the last occurrence of supplied substring in the string. Raise ValueError if not found.

str.rindex(sub[, start[, end]] )

split() – Return a list of words delimited by the provided subtring. If maximum number of split is specified, it is done from the left.

str.split([separator [, maxsplit]])

splitlines() – Return a list of lines in the string.

str.splitlines([keepends])

startswith() – Return true if the string starts with the provided substring.

str.startswith(prefix[, start[, end]])

strip() – Return a string with provided leading and trailing characters removed.

string.strip([chars])

swapcase() – Return a string with lowercase characters converted to uppercase and vice versa.

string.swapcase()

title() – Return a title (first character of each word capitalized, others lowercased) cased string.

str.title()

translate() – Return a copy of string that has been mapped according to the provided map.

string.translate(table)

upper() – Return a copy of all uppercased string.

string.upper()

zfill() – Return a numeric string left filled with zeros in the provided width.

str.zfill(width)

Some of the method examples are not given intentionally to get you try your self and play around the options available with the methods.

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate â‚ą42 per Tree.



About the Author


Coder, Blogger, Wanderer, Philosopher, Curious pumpkin



Tags: ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook