Strings and Character Data

Case Conversion

Converts the target string to “title case.”

'the sun also rises'.title()

# 'The Sun Also Rises'
'FOO Bar 123 baz qUX'.swapcase()  # āļŠāļĨāļąāļšāļ•āļąāļ§āđ€āļĨāđ‡āļāļ•āļąāļ§āđƒāļŦāļāđˆ

# 'foo bAR 123 BAZ Qux'

'FOO Bar 123 baz qUX'.upper() # āļ•āļąāļ§āļžāļīāļĄāļžāđŒāđƒāļŦāļāđˆāļ—āļąāđ‰āļ‡āļŦāļĄāļ”

# 'FOO BAR 123 BAZ QUX'

'FOO Bar 123 baz qUX'.lower()  # āļ•āļąāļ§āļžāļīāļĄāļžāđŒāđ€āļĨāđ‡āļāļ—āļąāđ‰āļ‡āļŦāļĄāļ”

# 'foo bar 123 baz qux'

s = 'foO BaR BAZ quX'  # āļ•āļąāļ§āļ­āļąāļāļĐāļĢāļ•āļąāļ§āđāļĢāļāđ€āļ›āđ‡āļ™āļ•āļąāļ§āļžāļīāļĄāļžāđŒāđƒāļŦāļāđˆ
s.capitalize()

#  'Foo bar baz qux'

str.split('a,b,c', ',')

# abc

'this is my string'.split()

#['this', 'is', 'my', 'string']

>>> s = ' this   is  my string '
>>> s.split()

#['this', 'is', 'my', 'string']

>>> s.split(' ')
#['', 'this', '', '', 'is', '', 'my', 'string', '']

# Limiting Splits With Maxsplit

>>> s = "this is my string"
>>> s.split(maxsplit=1)

#['this', 'is my string']

Check Special Character

# import required package 
import re 
  
# Function checks if the string 
# contains any special character 
def check_special_char(string): 
  
    # Make own character set and pass  
    # this as argument in compile method 
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
      
    # Pass the string in search  
    # method of regex object.     
    if(regex.search(string) == None): 
        print("String is accepted") 
          
    else: 
        print("String is not accepted.") 

# Enter the string 
string = "Geeks$For$Geeks"
      
# calling run function  
check_special_char(string)

 # String is not accepted. 

String Constant

import string

string.digits  # digit

# 0123456789

string.ascii_lowercase

# 'abcdefghijklmnopqrstuvwxyz'

string.ascii_uppercase

# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.ascii_letters

# 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.hexdigits

# 0123456789abcdefABCDEF

string.printable

# '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR
# STUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

Last updated