Python Strings
Published: 2023-05-11 06:58:51

#  Strings:

## What is a string in python?

Technically speaking, an  **immutable data sequence**  is known as a string in Python. In simple words, as discussed in the case of a crossword, a Python string is nothing but an array of characters, but a computer does not understand characters. It only understands the language of 0’s and 1’s.

So these characters are converted to a number so the computer can understand them clearly. This conversion is known as encoding. ASCII and Unicode are some of the popular encodings used.

To put it simply, Python strings are a sequence of  **Unicode characters**.

## Creating a String in Python

A string in Python can be easily created using single, double, or even triple quotes. The characters that form the string are enclosed within any of these quotes.

**Note:**  Triple quotes are generally used when we are working with multiline strings in Python and docstring in Python.

Let’s take a look at an example where we will create strings using the three types of quotes –

**Code:**

```python
single_string='Hello'
double_string="Hello World"
triple_string="""Welcome to Scaler"""
print(single_string)
print(double_string)
print(triple_string)

```

**Output:**

```python
Hello
Hello World
Welcome to Scaler
```

## Different Methods of Python String Module

Python has a plethora of built-in functions of the string module that can be used for string manipulations. Let's take a look at some of the commonly used functions.


capitalize():

Takes the first character of the string and converts it to upper case

casefold():

Converts the entire string into lowercase characters

center():

This function aligns the string in the 'center'

count():

The count() function will return the count of the specified character in the string

encode():

The encoded version of the string is returned

endswith():

As the function name suggests, it tests if a string ends with a specified substring

expandtabs():

This function sets the tab size of the specified string

find():

Looks for a specified string inside another string and returns the index where the substring was found

format():

The function we studied above, formats the specified values in the string

format_map():

Performs the same function as format()

index():

Looks for a specified character inside another string and returns the index where the substring was found

isalnum():

Boolean function that would return true if all the characters in the string are alphanumeric i.e. contain only numbers or alphabets and no special characters

[isalpha()](https://www.scaler.com/topics/isalpha-in-python/)

Boolean function that returns True if all the characters in the string are alphabets

isascii():

If all the characters in the string are ASCII characters, then this boolean function returns True

isdecimal():

If all the characters in the string are decimals (numbers) this boolean function returns True

isdigit():

Boolean function that would return true if all the characters in the string are digits

isidentifier():

If the string is an identifier, then this boolean function will return True

islower():

If all the characters in the string are in lowercase, then this boolean function returns True

isnumeric():

If all the characters in the string are numeric, then this boolean function returns True

isspace():

If the character is a space, then this function returns True

isupper():

If all the characters in the string are in uppercase, then this boolean function returns True

join():

This function takes an iterable and converts it into a string

lower():

This function converts the string into lowercase

replace():

Returns a string where a specified value is replaced with a specified value

rfind():

[rfind() function in python](https://www.scaler.com/topics/rfind-in-python/)  searches the string for a specified value and returns the last index of where it was found

rindex():

Searches the string for a specified value and returns the last index of where it was found

rstrip():

Returns a right trim version of the string

split():

Splits the string at the specified separator, and returns a list

splitlines():

[splitlines() in Python](https://www.scaler.com/topics/splitlines-in-python/)  splits the string at line breaks and returns a list

startswith():

The  [startswith() in python](https://www.scaler.com/topics/startswith-in-python/)  returns true if the string starts with the specified value

strip():

Returns a trimmed version of the string, i.e. without spaces at the start and end of the string

upper():

[upper()](https://www.scaler.com/topics/upper-in-python/)  converts a string into upper case


code :
```python
string1 = "123"
string2 = "abcd"
string3 = "12!cdef"
string4 = "ab cd"

print(string1.isnumeric())
print(string1.isalnum())
print(string2.isalpha())
print(string3.isalnum())
print(string4.isalpha())

```

**Output:**

```plaintext
True
True
True
False
False
```

### Syntax of Python String Split

```python
str.split(separator, maxsplit)

```

str: variable containing the input string. Datatype – string.

## Parameters of Split Function in Python

-   **separator:**  This is the delimiter. The string splits at this specified delimiter. This is optional, i.e., you may or may not specify a separator. In case no separator has been specified, the default separator is space. In the split() function, we can have one or more characters as delimiters, or we can also have two or more words as delimiters.
-   **maxsplit:**  This specifies the maximum number of times the string should be split. This is optional, i.e., you may or may not specify the maxsplit count. In case it has not been specified, the default value is -1, i.e., no limit on the number of splits. In case any negative value is entered, it works the same as in the case when no value is specified.



## Example of Python String Split()

### Without Specifying Any Maxsplit

### Case 1:

```python
str = 'InterviewBit is a great place for learning'
print(str.split())

```

In the above case, no separator has been specified, and hence the default separator i.e., space is taken to split the string. Also, we see that no maxsplit count is given, so the default value is -1, i.e., no limit on the number of splits. So the string is split wherever a space is found.

### Output:

```python
['InterviewBit', 'is', 'a', 'great', 'place', 'for', 'learning']

```

**Case 2**

```python
str = 'InterviewBit, is a, great place, for learning'
print(str.split(','))

```

In the above case, the separator has been specified, i.e., (",") comma. But since there is no  _maxsplit_  count, so the default value again is -1, i.e., no limit on the number of splits.

### Output:

```python
['InterviewBit', ' is a', ' great place', ' for learning']
```

## join():

## Syntax of  join()  Function in Python

The syntax of join() is as follows:

```pyhton
stringSeperator.join(iterable)

```

## Parameter of  join()  Function in Python

The join method takes a single parameter,

-   iterable: The iterable can be of any type, including List, Tuple, Dictionary, Set, and String.

## Return Value of  join()  Function in Python

**Return Type:**  string

It returns a string after concatenating all elements of iterable.

## Example of  join()  Function in Python

An example to show the working of join is as follows:

```python
elements = ['A', 'B', 'C', 'D']

str1 = ""
str2 = "-"

str1 = str1.join(elements)
str2 = str2.join(elements)

print(str1)
print(str2)

```

**Output:**

```python
ABCD
A-B-C-D
```