Hướng dẫn how to convert a string to a literal in python - làm thế nào để chuyển đổi một chuỗi thành một ký tự trong python

Đối với Python 3, cách để làm điều này không thêm dấu gạch chéo ngược và chỉ đơn giản là bảo tồn \n,

hello\nbobby\nsally\n
0, v.v. là:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

Mang lại một giá trị có thể được viết là CSV:

hello\nbobby\nsally\n

Tuy nhiên, dường như không có một giải pháp cho các nhân vật đặc biệt khác, tuy nhiên, có thể nhận được một \ trước họ. Đó là một người lập dị. Giải quyết điều đó sẽ phức tạp.

Ví dụ: để tuần tự hóa

hello\nbobby\nsally\n
1 chứa danh sách các chuỗi có ký tự đặc biệt trong TextFile ở định dạng mà Bert mong đợi với CR giữa mỗi câu và một đường trống giữa mỗi tài liệu:

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

Điều này xuất ra (cho tài liệu GitHub CodeSearchNet cho tất cả các ngôn ngữ được mã hóa thành câu):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

Chuyển đổi chuỗi thành chuỗi thô trong Python #

Để chuyển đổi chuỗi thành chuỗi thô:

  1. Sử dụng phương thức
    hello\nbobby\nsally\n
    
    2 để chuyển đổi chuỗi thành đối tượng byte.
  2. Sử dụng phương thức
    hello\nbobby\nsally\n
    
    3 để chuyển đổi đối tượng byte thành chuỗi thô.

Copied!

my_str = 'one\ttwo\nthree' print(repr(my_str)) # 👉️ 'one\ttwo\nthree' # ✅ Convert string to raw bytes object my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'one\\ttwo\\nthree' # ---------------------------------------------- # ✅ Convert string to raw string result = my_str.encode('unicode_escape').decode() print(result) # 👉️ one\ttwo\nthree

Chúng tôi đã sử dụng phương thức

hello\nbobby\nsally\n
2 để chuyển đổi chuỗi thành đối tượng byte với các ký tự thoát.

Phương thức str.encode trả về một phiên bản được mã hóa của chuỗi dưới dạng đối tượng byte. Mã hóa mặc định là

hello\nbobby\nsally\n
5.

Copied!

my_str = 'one\ttwo\nthree' # 👇️ with escape characters my_bytes = my_str.encode('unicode_escape') print(my_bytes) # 👉️ b'one\\ttwo\\nthree' # 👇️ without escape characters my_bytes = my_str.encode() print(my_bytes) # 👉️ b'one\ttwo\nthree'

Lưu ý rằng khi chúng tôi sử dụng mã hóa

hello\nbobby\nsally\n
6, một dấu gạch chéo ngược được thêm vào.

Sử dụng phương thức

hello\nbobby\nsally\n
7 để chuyển đổi đối tượng byte thành chuỗi.

Copied!

my_str = 'one\ttwo\nthree' result = my_str.encode('unicode_escape').decode() print(result) # 👉️ one\ttwo\nthree

Phương thức byte.decode trả về một chuỗi được giải mã từ các byte đã cho. Mã hóa mặc định là

hello\nbobby\nsally\n
5.

Mã hóa là quá trình chuyển đổi

hello\nbobby\nsally\n
9 thành đối tượng
with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
0 và giải mã là quá trình chuyển đổi đối tượng
with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
0 thành
hello\nbobby\nsally\n
9.

Nếu bạn có quyền truy cập vào khai báo của biến, bạn có thể tiền tố chuỗi với

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
3 để đánh dấu nó thành một chuỗi thô.

Copied!

my_str = r'one\ttwo\nthree' print(my_str) # 👉️ 'one\ttwo\nthree'

Các chuỗi được tiền tố với

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
3 được gọi là chuỗi thô và coi các dấu gạch chéo ngược là ký tự theo nghĩa đen.

Nếu bạn cần nội suy một biến trong một chuỗi thô, hãy sử dụng một chuỗi được định dạng theo nghĩa đen.

Copied!

variable = 'two' my_str = fr'one\t{variable}\nthree' print(my_str) # 👉️ 'one\ttwo\nthree'

Chuỗi được định dạng theo nghĩa đen (F-Strings) Hãy cho chúng tôi bao gồm các biểu thức bên trong chuỗi bằng cách tiền tố chuỗi với

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
5.

Hãy chắc chắn để bọc các biểu thức trong niềng răng xoăn -

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
6.

Lưu ý rằng chúng tôi đã có tiền tố chuỗi với

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
7 và không chỉ với
with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')
5.

Làm thế nào để bạn chuyển đổi một chuỗi thành một chuỗi theo nghĩa đen trong Python?

Sử dụng hàm tích hợp repr () để chuyển đổi các chuỗi bình thường thành các chuỗi thô. Chuỗi được trả về bởi repr () có 'ở đầu và cuối. Sử dụng các lát cắt, bạn có thể nhận được chuỗi tương đương với chuỗi RAW.. The string returned by repr() has ' at the beginning and the end. Using slices, you can get the string equivalent to the raw string.

Làm thế nào để bạn chuyển đổi chuỗi thành nghĩa đen?

Đặt con trỏ văn bản hoặc chuột lên chuỗi thoát ra để chuyển đổi ..
Tiếp theo, làm một trong những điều sau đây: bàn phím.Nhấn Ctrl+.Để kích hoạt menu Action và Refactorings nhanh và chọn Chuyển đổi thành Chuỗi thô theo nghĩa đen từ menu ngữ cảnh.Con chuột.....
Chuỗi sẽ được chuyển đổi ngay lập tức thành một chuỗi thô theo nghĩa đen ..

Một chuỗi có thể là một theo nghĩa đen trong Python?

Một chuỗi theo nghĩa đen có thể được tạo bằng cách viết một văn bản (một nhóm các ký tự) được bao quanh bởi một câu nói đơn (), gấp đôi (phạm vi) hoặc ba trích dẫn.Bằng cách sử dụng trích dẫn ba, chúng ta có thể viết các chuỗi nhiều dòng hoặc hiển thị chúng theo cách mong muốn.Ví dụ: Ở đây Geekforgeek là một chuỗi theo nghĩa đen được gán cho một biến.. By using triple quotes we can write multi-line strings or display them in the desired way. Example: Here geekforgeeks is a string literal that is assigned to a variable(s).

\ R làm gì trong Python?

Trong các chuỗi Python, dấu gạch chéo ngược "\" là một nhân vật đặc biệt, còn được gọi là nhân vật "Escape".Nó được sử dụng để thể hiện các ký tự khoảng trắng nhất định: "\ t" là một tab, "\ n" là một dòng mới và "\ r" là một sự trở lại vận chuyển.Ngược lại, tiền tố một ký tự đặc biệt với "\" biến nó thành một ký tự thông thường.carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.