reCAPTCHA WAF Session Token

Python String Methods, with Examples — SitePoint


In this article, we’ll cover useful Python string methods for manipulating string (str) objects — such as joining, splitting and capitalizing. Each method described in this article will include an explanation with a relevant example. We’ll also end with a little challenge you should try to assess how much you’ve understood the topic.

Strings are an integral part of every programming language, and are one of the most-used data types in Python. They constitute sequences that, when grouped together, can form words, sentences, and so on. Like every other programming language, Python has its own unique implementation of the string data type. Strings are a sequence of immutable unicode characters, enclosed within single, double or triple quotes. An “immutable” string is one that, once declared, cannot be modified; instead, another string object is created.

Note: this article focuses on Python 3. Python 2 uses the unicode() function to do the same things we’ll discuss here. Also note that the old str() class from Python 2 has become the bytes() class in Python 3.

A Python string looks like this:

<code class="python language-python">greeting <span class="token operator">=</span> <span class="token string">"Hello, World!"</span>
</code>

Note: unlike Java or other programming languages, Python doesn’t support a character data type. So a single character enclosed in quotes like 'c' is still a string.

In Python, the bytes() class returns an immutable sequence of bytes objects. They have a prefix b within single quotes '', represented in the form b'xxx'. However, like string literals, bytes literals can also have single, double or triple quotes.

Table of Contents
  1. Text Sequence Type and the str Class
  2. Python String Methods: Overview
  3. Python String Methods that Return a Modified Version of a String
  4. Python String Methods for Joining and Splitting Strings
  5. Python String Methods for Performing Queries on a String
  6. Python String Methods for Returning a Boolean Value
  7. Python Bytes Methods that Return a String
  8. Conclusion
  9. Challenge

Text Sequence Type and the str Class

Strings are one of Python’s built-in types. This means that string data types, like other types, are built into the Python interpreter.

Written text in Python is created by string objects or string literals. Python string literals can be written with single, double or triple quotes. When a single quote is used for a string literal, a double quote can be embedded without any errors, and vice versa. Triple quotes allows for strings that can span multiple lines without the use of a backslash to escape newline characters.

Here’s a string literal with single quotes:

<code class="python language-python">string_one <span class="token operator">=</span> <span class="token string">'String one'</span>
</code>

Here’s a string literal with double quotes:

<code class="python language-python">string_two <span class="token operator">=</span> <span class="token string">"String two"</span>
</code>

Here’s a string literal with triple quotes:

<code class="python language-python">string_three <span class="token operator">=</span> <span class="token triple-quoted-string string">"""
This string covers
more than one
line.
"""</span>
</code>

Strings can also be created through the use of the str constructor from other objects. The str() constructor returns a printable string version of a given object.

The Python str class can be used to create string objects. The str() constructor can take an object as argument and implicitly calls the object’s dunder __str__() to return a string representation of that object:

<code class="python language-python">number <span class="token operator">=</span> <span class="token number">23</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>number<span class="token punctuation">,</span> <span class="token string">'is an object of '</span><span class="token punctuation">,</span> <span class="token builtin">type</span><span class="token punctuation">(</span>number<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token builtin">dir</span><span class="token punctuation">(</span>number<span class="token punctuation">)</span><span class="token punctuation">)</span>
number <span class="token operator">=</span> <span class="token builtin">str</span><span class="token punctuation">(</span>number<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>number<span class="token punctuation">,</span> <span class="token string">'is an object of '</span><span class="token punctuation">,</span> <span class="token builtin">type</span><span class="token punctuation">(</span>number<span class="token punctuation">)</span><span class="token punctuation">)</span>
</code>

Here’s the output of the above code:

<code class="python language-python"><span class="token number">23</span> <span class="token keyword">is</span> an <span class="token builtin">object</span> of <span class="token operator"><</span><span class="token keyword">class</span> <span class="token string">'int'</span><span class="token operator">></span>
<span class="token number">23</span> <span class="token keyword">is</span> an <span class="token builtin">object</span> of <span class="token operator"><</span><span class="token keyword">class</span> <span class="token string">'str'</span><span class="token operator">></span>
</code>

The variable number was initially an int object. Hhowever, the str constructor converts it to string object.

Every Python object has the str() dunder method, which computes a string version of that object.

A simple peek at an object’s properties and methods with the dir() built-in function will show the __str__() method, among others. We can create a string version of an object out of a particular object by explicitly calling its __str__() method, as seen in the example below:

<code class="python language-python">price <span class="token operator">=</span> <span class="token number">15.25</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token builtin">dir</span><span class="token punctuation">(</span>price<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token builtin">type</span><span class="token punctuation">(</span>price<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token builtin">type</span><span class="token punctuation">(</span>price<span class="token punctuation">.</span>__str__<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
</code>

Here’s the output of the above code:

<code class="bash language-bash"><span class="token punctuation">[</span><span class="token punctuation">..</span>.
<span class="token string">'__sizeof__'</span>, <span class="token string">'__str__'</span>, <span class="token string">'__sub__'</span>, 
<span class="token punctuation">..</span>.<span class="token punctuation">]</span>
<span class="token operator"><</span>class <span class="token string">'float'</span><span class="token operator">></span>
<span class="token operator"><</span>class <span class="token string">'str'</span><span class="token operator">></span>
</code>

Python String Methods: Overview

Since strings are regarded as sequences in Python, they implement all sequence operations, such as concatenation, slice, and so on:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> word <span class="token operator">=</span> <span class="token string">'golden'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token builtin">len</span><span class="token punctuation">(</span>word<span class="token punctuation">)</span>
<span class="token number">6</span>
<span class="token operator">>></span><span class="token operator">></span> word <span class="token operator">+</span> <span class="token string">'age'</span>
<span class="token string">'goldenage'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'la'</span> <span class="token operator">*</span> <span class="token number">3</span>
<span class="token string">'lalala'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

Apart from string sequence operations, there are other additional methods related to string objects. Some of these methods are useful for formatting strings, searching for a substring within another string, trimming whitespace, and performing certain checks on a given string, and so on.

It’s worth noting that these string methods don’t modify the original string; since strings are immutable in Python, modifying a string is impossible. Most of the string methods only return a modified copy of the original string, or a Boolean value, as the case may be.

Let’s now do a breakdown of some Python string methods, with examples.

Python String Methods that Return a Modified Version of a String

str.capitalize()

This method returns a copy of the string with its first character capitalized and the others in lowercase.

Example 1:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">"i Enjoy traveling. Do you?"</span><span class="token punctuation">.</span>capitalize<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token string">'I enjoy traveling. do you?'</span>
<span class="token operator">>></span><span class="token operator">></span>
</code>

str.center(width[, fillchar])

This method returns a centered string padded by a given fillchar and width. If the width is equal to or less than the length of the string len(s), the original string is returned.

The method takes two parameters: width and fillchar. The width indicates the length of the string, including the padding character. fillchar is an optional parameter that’s used for padding the string.

Example 2:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> sentence <span class="token operator">=</span> <span class="token string">'i Enjoy traveling. Do you?'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token builtin">len</span><span class="token punctuation">(</span>sentence<span class="token punctuation">)</span>
<span class="token number">26</span>
<span class="token operator">>></span><span class="token operator">></span> sentence<span class="token punctuation">.</span>center<span class="token punctuation">(</span><span class="token number">31</span><span class="token punctuation">)</span>
<span class="token string">'  i Enjoy traveling. Do you? '</span>
<span class="token operator">>></span><span class="token operator">></span> sentence<span class="token punctuation">.</span>center<span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span>
<span class="token string">' i Enjoy traveling. Do you? '</span>
</code>

This method returns a string encoded in bytes.

By default, strings passed to the function are encoded to utf-8, and a UnicodeEncodeError exception is raised when an error occurs. The errors keyword argument specifies how errors are handled — such as strict, which raises an exception, and ignore, which ignores any errors encounter, and so on. There are some other encoding options to check out.

Example 3:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> sentence <span class="token operator">=</span> <span class="token string">"i Enjoy traveling. Do you, 山本さん?"</span>
<span class="token operator">>></span><span class="token operator">></span> sentence<span class="token punctuation">.</span>encode<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token string">b'i Enjoy traveling. Do you, \xe5\xb1\xb1\xe6\x9c\xac\xe3\x81\x95\xe3\x82\x93?'</span>
<span class="token operator">>></span><span class="token operator">></span> sentence<span class="token punctuation">.</span>encode<span class="token punctuation">(</span>encoding<span class="token operator">=</span><span class="token string">'ascii'</span><span class="token punctuation">)</span>
Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
 File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">1</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator"><</span>module<span class="token operator">></span>
UnicodeEncodeError<span class="token punctuation">:</span> <span class="token string">'ascii'</span> codec can't encode characters <span class="token keyword">in</span> position <span class="token number">27</span><span class="token operator">-</span><span class="token number">30</span><span class="token punctuation">:</span> ordinal <span class="token keyword">not</span> <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">128</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> sentence<span class="token punctuation">.</span>encode<span class="token punctuation">(</span>encoding<span class="token operator">=</span><span class="token string">'ascii'</span><span class="token punctuation">,</span> errors<span class="token operator">=</span><span class="token string">'replace'</span><span class="token punctuation">)</span>
<span class="token string">b'i Enjoy traveling. Do you, ?????'</span>
</code>

You can read more about exception handling in A Guide to Python Exception Handling.

str.format(*args, **kwargs)

This method returns a copy of the string, where each replacement field is replaced with the string value of the corresponding argument. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument.

The braces ({}) serve as a placeholder for positional *args or keyword **kwargs arguments that are passed in to the format() method.

Example 4:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">"I bought {0} apples and the cost {1:.2f} Ghana cedis."</span><span class="token punctuation">.</span><span class="token builtin">format</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">18.70</span><span class="token punctuation">)</span>
<span class="token string">'I bought 2 apples and the cost 18.70 Ghana cedis.'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">"My name is {first_name}, and I'm a {profession}."</span><span class="token punctuation">.</span><span class="token builtin">format</span><span class="token punctuation">(</span>first_name<span class="token operator">=</span><span class="token string">'Ben'</span><span class="token punctuation">,</span> profession<span class="token operator">=</span><span class="token string">'doctor'</span><span class="token punctuation">)</span>
<span class="token string">"My name is Ben, and I'm a doctor."</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

In the example above, {0} is a placeholder for the first argument 2 in the format() method. {1:.2f} acts in place for 18.70. The .2f indicates that the output should display the floating point number with two decimal places.

first_name and profession are placeholders for keyword arguments passed to the format() method.
More on string format syntax can be found in the Python documentation.

str.lower()

This method returns a copy of the string with any character in uppercase to lowercase.

Example 5:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>lower<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token string">'i enjoy traveling. do you?'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.removeprefix(prefix, /)

This method returns a copy of the string with the specified prefix removed. Where the specified prefix is not found, the original string is returned.

Example 6:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>removeprefix<span class="token punctuation">(</span><span class="token string">'i'</span><span class="token punctuation">)</span>
<span class="token string">' Enjoy traveling. Do you?'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.removesuffix(suffix, /)

This method returns a copy of the string with the specified suffix removed. Where the specified suffix isn’t found, the original string is returned.

Example 7:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>removesuffix<span class="token punctuation">(</span><span class="token string">'Do you?'</span><span class="token punctuation">)</span>
<span class="token string">'i Enjoy traveling. '</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

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

This method returns a string with all occurrences of the substring old substituted by the new. If the count argument is given, all count number of occurrences are replaced.

Example 8:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">'Enjoy'</span><span class="token punctuation">,</span><span class="token string">'dislike'</span><span class="token punctuation">)</span>
<span class="token string">'i dislike traveling. Do you?'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'Things fall apart'</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">'a'</span><span class="token punctuation">,</span><span class="token string">'e'</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token string">'Things fell apart'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.strip([chars])

This method returns a new string with characters specified in the argument removed from the beginning and the end of the old string. By default, it removes whitespace where a chars argument isn’t provided.

The strip() method operation is done on a per-character basis, rather than a per-string basis.

Example 9:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> word1 <span class="token operator">=</span> <span class="token string">' whitespace '</span><span class="token punctuation">.</span>strip<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> word1
<span class="token string">'whitespace'</span>
<span class="token operator">>></span><span class="token operator">></span> word2 <span class="token operator">=</span> <span class="token string">'exercise'</span><span class="token punctuation">.</span>strip<span class="token punctuation">(</span><span class="token string">'e'</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> word2
<span class="token string">'xercis'</span>
<span class="token operator">>></span><span class="token operator">></span> word3 <span class="token operator">=</span> <span class="token string">'chimpanze'</span><span class="token punctuation">.</span>strip<span class="token punctuation">(</span><span class="token string">'acepnz'</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> word3
<span class="token string">'him'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

As seen in the example above, where the chars argument is not specified, the whitespace in word1 is removed. When the string referenced by the word2 variable had its strip() method invoked with the e argument, the leading and trailing e characters are absent from the returned value.

In word3, some random characters are passed as an argument, and these characters are stripped out from the beginning of the string and the end of the string — until there’s a character in the string that doesn’t match any in the argument.

str.title()

This method returns a copy of the string, where every word starts with an uppercase character and the remaining characters are lowercase.

The title() method converts the first character of every word to uppercase — whether definite articles like “the”, prepositions, and so on.

Example 10:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>title<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token string">'I Enjoy Traveling. Do You?'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.upper()

This method returns a copy of the string with all characters converted to uppercase.

Example 11:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>upper<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token string">'I ENJOY TRAVELING. DO YOU?'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

Python String Methods for Joining and Splitting Strings

str.join(iterable)

This method returns a string made by concatenating other strings in an iterable. If the iterable has non-string values, a TypeError exception is raised.

Example 12:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> words <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"Accra"</span><span class="token punctuation">,</span> <span class="token string">"is"</span><span class="token punctuation">,</span> <span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"beautiful"</span><span class="token punctuation">,</span> <span class="token string">"city"</span><span class="token punctuation">]</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">' '</span><span class="token punctuation">.</span>join<span class="token punctuation">(</span>words<span class="token punctuation">)</span>
<span class="token string">'Accra is a beautiful city'</span>
<span class="token operator">>></span><span class="token operator">></span> names <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'Abe'</span><span class="token punctuation">,</span> <span class="token string">'Fred'</span><span class="token punctuation">,</span> <span class="token string">'Bryan'</span><span class="token punctuation">]</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'-'</span><span class="token punctuation">.</span>join<span class="token punctuation">(</span>names<span class="token punctuation">)</span>
<span class="token string">'Abe-Fred-Bryan'</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.split(sep=None, maxsplit=- 1)

This method returns a list of the words or characters in a string split at a specified separator.

The method takes two parameters:

  • sep: a separator/delimiter that indicates where the split occurs. If it isn’t provided, whitespaces are used.
  • maxsplit: indicates the maximum number of splits allowed. If it isn’t provided, all possible splits are executed

Example 13:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>split<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token string">'i'</span><span class="token punctuation">,</span> <span class="token string">'Enjoy'</span><span class="token punctuation">,</span> <span class="token string">'traveling.'</span><span class="token punctuation">,</span> <span class="token string">'Do'</span><span class="token punctuation">,</span> <span class="token string">'you?'</span><span class="token punctuation">]</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>split<span class="token punctuation">(</span><span class="token string">' '</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span>
<span class="token punctuation">[</span><span class="token string">'i'</span><span class="token punctuation">,</span> <span class="token string">'Enjoy'</span><span class="token punctuation">,</span> <span class="token string">'traveling. Do you?'</span><span class="token punctuation">]</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

Python String Methods for Performing Queries on a String

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

This method returns the number of times a substring occurs within the given string. It takes two optional arguments — start and end — that indicate where the count begins and stops.

Example 14:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i enjoy traveling. do you?'</span><span class="token punctuation">.</span>count<span class="token punctuation">(</span><span class="token string">'e'</span><span class="token punctuation">)</span>
<span class="token number">2</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

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

This method returns the index of the first occurrence where the substring is found within the original string. It takes the slice form s[start:end]. If the substring isn’t found, -1 is returned.

The find() method makes use of slicing to find a substring within another substring. Slicing in Python means the extracting of a subsequence, and in this case a substring from another string sequence by the use of index points, start and stop.

A Python slice has the following notion:

<code class="python language-python">sequence<span class="token punctuation">[</span>start<span class="token punctuation">:</span>stop<span class="token punctuation">]</span>
</code>

With the find() method, the search goes from the beginning of the string to the end if start and stop index points aren’t given. When the substring is found, the method returns an integer indicating the index of the first character of the substring.

The method takes three parameters:

  • sub: the substring being searched for in the original string
  • start: indicates where the search should begin
  • end: indicates where the search should stop

Example 15:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>find<span class="token punctuation">(</span><span class="token string">'traveling'</span><span class="token punctuation">)</span>
<span class="token number">8</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'I live in Accra Ghana'</span><span class="token punctuation">.</span>find<span class="token punctuation">(</span><span class="token string">'acc'</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">)</span>
<span class="token operator">-</span><span class="token number">1</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

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

This method returns the index of a substring within the original string. It works just like the find() method, except that it raises a ValueError exception when the substring isn’t found.

The method takes three parameters:

  • sub: the substring being searched for in the original string
  • start: indicates where the search should begin
  • end: indicates where the search should stop

Example 16:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>index<span class="token punctuation">(</span><span class="token string">'car'</span><span class="token punctuation">)</span>
Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
 File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">1</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator"><</span>module<span class="token operator">></span>
ValueError<span class="token punctuation">:</span> substring <span class="token keyword">not</span> found
<span class="token operator">>></span><span class="token operator">></span> 
</code>

As seen in the code snippet above, a ValueError exception is raised because there’s no substring car found in our original string.

Python String Methods for Returning a Boolean Value

str.endswith(suffix[, start[, end]])

This method returns True if the string ends with the specified suffix; otherwise, it returns False.

The suffix[, start[, end]] means that the search for the substring will start at beginning of the string or a given index start until the end of the string or a given index end.

The method takes three parameters:

  • suffix: a string or tuple to be searched for
  • start: indicates where the search for the suffix should begin
  • end: indicates where the search for the suffix should stop

Example 17:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>endswith<span class="token punctuation">(</span><span class="token string">'you?'</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.isalnum()

This method returns True if the string contains alphanumeric characters and there’s at least one character; otherwise, it returns False.

Example 18:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>isalnum<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.isalpha()

This method returns True if all the string’s characters are alphabetic and there’s at least one character; otherwise, it returns False.

Example 19:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">" <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1998"  title="Python"   target="_blank" >Python</a>"</span><span class="token punctuation">.</span>isalnum<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">" <a href="https://yourselfhood.com/how-to-write-efficient-python-code-a-tutorial-for-beginners/"  class="lar_link" data-linkid="2205" data-postid="1998"  title="Python"   target="_blank" >Python</a>."</span><span class="token punctuation">.</span>isalnum<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">"パイソン"</span><span class="token punctuation">.</span>isalnum<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">"パイソン。"</span><span class="token punctuation">.</span>isalnum<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.isascii()

This method returns True if all characters in the string are ASCII or it’s empty; otherwise, it returns False.

Example 20:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>isascii<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">"体当たり"</span><span class="token punctuation">.</span>isascii<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span>
</code>

str.isdecimal()

This method returns True if the string contains all decimal characters and there’s at least one character; otherwise, it returns False.

Example 21:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>isdecimal<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'10'</span><span class="token punctuation">.</span>isdecimal<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span>
</code>

str.isnumeric()

This method returns True if the string contains all numeric characters and there’s at least one character; otherwise, it returns False.

Example 22:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>isnumeric<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'1000.04'</span><span class="token punctuation">.</span>isnumeric<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'1000'</span><span class="token punctuation">.</span>isnumeric<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.islower()

This method returns True if the string’s characters are all lowercase and there’s at least one cased character; otherwise, it returns False.

Example 23:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>islower<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i enjoy traveling. do you?'</span><span class="token punctuation">.</span>islower<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

str.isupper()

This method returns True if the string’s characters are all in uppercase and there’s at least one cased character; otherwise, it returns False.

Example 24:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>isupper<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">False</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">'I ENJOY TRAVELING. DO YOU?'</span><span class="token punctuation">.</span>isupper<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

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

This method returns True if the string ends with the specified prefix; otherwise, it returns False.

The method takes three parameters:

  • suffix: a string or tuple to be searched for
  • start: indicates where the search for the prefix should begin
  • end: indicates where the search for the prefix should stop

Example 25:

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">'i Enjoy traveling. Do you?'</span><span class="token punctuation">.</span>startswith<span class="token punctuation">(</span><span class="token string">'i'</span><span class="token punctuation">)</span>
<span class="token boolean">True</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

Python Bytes Methods that Return a String

This method returns a string decoded from bytes.

By default, encoding is in 'utf-8', and a UnicodeDecodeError exception is raised when an error occurs. strict, ignore and replace are error keyword arguments that dictate how exceptions are handled.

Example 26

<code class="python language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token string">b'i Enjoy traveling. Do you, \xe5\xb1\xb1\xe6\x9c\xac\xe3\x81\x95\xe3\x82\x93?'</span><span class="token punctuation">.</span>decode<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token string">'i Enjoy traveling. Do you, 山本さん?'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token string">b'i Enjoy traveling. Do you, \xe5\xb1\xb1\xe6\x9c\xac\xe3\x81\x95\xe3\x82\x93?'</span><span class="token punctuation">.</span>decode<span class="token punctuation">(</span>encoding<span class="token operator">=</span><span class="token string">'ascii'</span><span class="token punctuation">)</span>
Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
 File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">1</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator"><</span>module<span class="token operator">></span>
UnicodeDecodeError<span class="token punctuation">:</span> <span class="token string">'ascii'</span> codec can't decode byte <span class="token number">0xe5</span> <span class="token keyword">in</span> position <span class="token number">27</span><span class="token punctuation">:</span> ordinal <span class="token keyword">not</span> <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token number">128</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> 
</code>

Conclusion

It’s important to be able to manipulate strings of text in programming — such as when formatting user input.

Python has strings but no character data type. So this 'c' is very much a string, as is 'character'.

Unlike C-typed programming languages, Python has some nifty methods for formatting strings and also performing checks on those strings with less code.

Challenge

Using the information contained this article, can you figure out what the output will be just by reading the following line of code? What will be returned from the following?

<code class="python language-python"><span class="token string">"-"</span><span class="token punctuation">.</span>join<span class="token punctuation">(</span><span class="token string">"tenet"</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">"net"</span><span class="token punctuation">,</span> <span class="token string">"ten"</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token punctuation">:</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>split<span class="token punctuation">(</span><span class="token string">"e"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">"-"</span><span class="token punctuation">,</span> <span class="token string">"e"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">"net"</span><span class="token punctuation">,</span> <span class="token string">"ten"</span><span class="token punctuation">)</span>
</code>

Paste it into an interactive Python session to check your answer. Were you able to figure it out?





Source link

Leave a Reply

Your email address will not be published. Required fields are marked *

WP Twitter Auto Publish Powered By : XYZScripts.com